• Resolved toneburst

    (@toneburst)


    I’m writing a sidebar widget plugin that scans posts in a selected category for embedded YouTube videos, and displays the first one found using oEmbed.

    Works great, but I’d like to ensure that the displayed post does not also appear on the Homepage.

    To do that, I tried adding

    // Hide category from Homepage if option set
    add_filter( 'pre_get_posts', function( $query ) {
       if( $instance[ 'excludeCategory' ] == 'on' ) {
    	   if( $query->is_home )
    		   $query->set( 'category__not_in', array( $instance[ 'category' ] ) );
       }
       return $query;
    } );

    to the constructor function of my plugin.

    This doesn’t work, and I suspect I know why. The main query that retrieves the posts in the primary loop must run before the widget is able to modify it.

    Am I right on this, and if so, is there any way to get this to work, or will I have to build a separate non-widget plugin to be able to achieve what I want?

    Cheers,

    a|x

Viewing 3 replies - 1 through 3 (of 3 total)
  • Whether your plugin has a widget or not is a bit of a red herring. However, you’re right – the $instance variable isn’t initialized until WordPress loads your widget, and the “pre_get_posts” – filter runs before that. Are you seeing “unitialized variable” errors in your debug.log file?

    What you need to do is store the information about which category you want to exclude in an option field instead of in the widget – so, if you are configuring this with a widget, you’ll need to add something to the “save” function to update a site option.

    One tool you can use to troubleshoot this is the super-fabulous Query Monitor plugin – Install it and it will tell you what hooked functions are run as the page is rendered. That will give you a better understanding of the order of things.

    Thread Starter toneburst

    (@toneburst)

    Hi ancawonka,

    thanks very much for getting back to me.

    I added

    // Save site options (required so constructor function can get option before widget loaded)
    update_option( 'ell_catvideo_excludeCat', $instance[ 'excludeCategory' ] );
    update_option( 'ell_catvideo_catID', $instance[ 'category' ] );

    to the update function, then retrieved the value with

    // Hide category from Homepage if option set
    add_filter( 'pre_get_posts', function( $query ) {
    	if( get_option( 'ell_catvideo_excludeCat' ) == 'on' ) {
    		if( $query->is_home )
    			$query->set( 'category__not_in', array( get_option( 'ell_catvideo_catID' ) ) );
    	}
    	return $query;
    } );

    in the widget constructor and used to to filter the other wp_queries made on the homepage.

    All working, now.

    Thanks very much for your help!

    a|x

    Glad to be of help! I especially love your function names, and cat videos. ??

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Widget Excluding Posts Homepage. Possible?’ is closed to new replies.