WordPress.org

Ready to get started?Download WordPress

Forums

set a hook depending on widget setting (1 post)

  1. hagenaer
    Member
    Posted 4 years ago #

    I've just created my first widget and it works like a charm (pulls random post(s) from specific category), thanks to the great codex documentation and plethora of great blog posts on the subject around the interwebs. Next feature I'd like to add to it is to hide the category the widget pulls posts from from showing in other areas of the blog, such as posts and pulldowns/menus. The code I found to do this comes from:
    http://zeo.unic.net.my/exclude-category-in-wordpress/

    function exclude_category($query) {
    	$query->set('cat', '-5');
    return $query;
    }
    add_filter('pre_get_posts', 'exclude_category');

    There are three (and possibly more) problems with this:
    1. The custom WP_Query() I use to pull the content for the widget now has no access to the category anymore either and pulls from cat=1 instead. I thought I could re-enable the category when starting the widget() function and disabling at the end, but I haven't gotten that to work yet.
    2. It only hides posts from the_loop, not from pulldowns/menus.
    3. Most difficultly--and this is really why I'm writing here--it should only hide this category if the checkbox for this option in the widget settings has been set. The big problem here I think is that the widget only gets rendered in the sidebar (or elsewhere) and by then it's too late to exclude the category from the main loop. The widget should add the filter at WP initialization, but only depending on a setting that's local to the widget instance. And... it should be able to do this for every widget instance that is used, so if it's used twice for different categories, and both have their hide_category set, both should be hidden before starting the main loop (and unlocked for the widget itself, see 1)

    Any thoughts on how to accomplish the above?

    Many thanks!

Topic Closed

This topic has been closed to new replies.

About this Topic