views:

246

answers:

1

How do I restrict all WordPress widgets to a given category? Such as, have a popdown listbox on my sidebar that lets me choose a bird category and all the widget data on that sidebar stick with that given bird category. I'm thinking I need some kind of filter with add_filter() but don't understand the process. The docs on this are incomplete.

A: 

I was very nervous about using the query filter because it's too native to the SQL API of WordPress and therefore potentially possible to break in future releases of WordPress -- especially since at the time of this StackOverflow answer here the WordPress 3.0 release is coming fairly soon and may introduce some dramatic changes.

The fix was to focus on replacing widget content entirely. Here's an example:

<?php 
add_filter('dynamic_sidebar_params','filterWidget');
function filterWidget($args) {
  switch($args[0]['widget_name']) {
    case 'Meta':
    case 'Categories':
    case 'Pages':
      return 0; //hide widget output
      break;
    case 'Links':
      //display new widget replacement output
      echo '<li class="widget"><h2 class="widgettitle">Links</h2>Hello world</li>';
      return 0; //hide previous widget output
      break;
    default:
      //echo "<br /><br />";
      //print_r($args);
      //echo "<br /><br />";
      return $args;
  } //end switch
}

In this example, if you stick it at the top of your theme's sidebar.php file, it will hide the Meta, Categories, and Pages widgets entirely, replace the Blogroll (aka Links) Widget with entirely new content, and then let every other widget you have display normally.

This resolves my problem because now I can redraw these widgets but this time do so with category restriction. As far as I know thus far, I can use a little bit of the WordPress Codex to get the data I need for these widgets to display, filter by category if I want, and then I can even use some routines that do things like draw a calendar or a tag cloud.

Volomike