Page 1 of 1

Restricting WordPress Widgets Per Category

Posted: Sun Feb 28, 2010 6:08 pm
by volomike
I do custom WordPress theming. I have an unusual client request. He wants to take all the default sidebar widgets and restrict them to category, such as Calendar, Tag Cloud, Recent Comments, etc. Anyone know how to do that?

I found that I can use the add_filter() hook API such that I can intercept all SQL queries in sidebar.php, and adjust them with:

Code: Select all

add_filter('query','myQueryFilterCallback');
function myQueryFilterCallback($args) {
print_r($args);
echo "<br />"
return $args;
}
The only trouble is, I cannot predict what widget a given query is running for. Besides, editing pure SQL is a bit risky because during upgrades of WP the query could be dramatically different.

Re: Restricting WordPress Widgets Per Category

Posted: Mon Mar 01, 2010 1:09 pm
by greyhoundcode
When you say the "default sidebar widgets", do you mean the usual stuff that is outputted in a typical theme following:

Code: Select all

<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar() ) : ?>
It's an interesting problem, my instincts are that there is no easy fix for achieving this from within a theme, though there may well be a very complicated fix.

I'm sure what I'm about to propose is exactly what you wish to avoid, but in this case might it not be easiest to copy each of the relevant widgets code into a new plugin, amending the queries appropriately, then use the new template tags that the plugin generates within your theme, if that makes sense?

Inelegant I know.

Re: Restricting WordPress Widgets Per Category

Posted: Mon Mar 01, 2010 1:34 pm
by volomike
greyhound, your instincts were right. The best choice appears to be to follow this method:

http://stackoverflow.com/questions/2346 ... o-category

and more importantly:

http://stackoverflow.com/questions/2346 ... n-category

Re: Restricting WordPress Widgets Per Category

Posted: Mon Mar 01, 2010 11:00 pm
by josh
Stack overflow lets you answer (and even accept answers for?) your own questions?.. weird

Re: Restricting WordPress Widgets Per Category

Posted: Tue Mar 02, 2010 2:35 am
by matthijs
Maybe I don't understand the problem, but can't you do what you want with conditional tags?
http://codex.wordpress.org/Conditional_Tags

is_category(), is_home(), !in_category( array( 4,5,6 ) ) , etc

Then show what you want depending on the condition

Re: Restricting WordPress Widgets Per Category

Posted: Tue Mar 02, 2010 10:29 am
by greyhoundcode
Volomike at StackOverflow wrote:the WordPress 3.0 release is coming fairly soon and may introduce some dramatic changes.
That's for sure. Especially if clients have administrator permissions and can click on the "automatically update to the latest version" link, potentially causing breakages elsewhere.