Many times I’ve needed to display or hide a widget based on some condition. Usually that condition is which page is being served. That’s easy enough with my own widgets by wrapping the output in an if statement employing a built-in WordPress Conditional Tag. The same can of course be done by directly editing 3rd-party widgets/plugins.
What if you need to change the behavior of a 3rd-party widget, but don’t want to alter it’s code? There’s a great plugin called Widget Logic that can help you do just that. The only caveat is that it directly runs code that you input. That opens up a security hole by executing code stored in the database. Not always a show stopper, but when developing for clients I try to play it safe.
Almost all the code and comments below are borrowed directly from the Widget Logic plugin. I’ve greatly simplified it to effect only the widget(s) and condition(s) hard coded. Also I removed the filtering function, as I was only using this to hide or show a widget. If you want to alter the output of a widget, it’s a pretty simple copy and paste from the original plugin to the second function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
// CALLED ON 'dynamic_sidebar_params' FILTER - this is called during 'dynamic_sidebar' just before each callback is run // swap out the original call back and replace it with our own function widget_restrict_widget_display_callback($params) { global $wp_registered_widgets; $id=$params[0]['widget_id']; if ($id == '/*INSERT WIDGET ID HERE*/' && /*INSERT CONDITIONAL TAGS HERE*/) { $wp_registered_widgets[$id]['callback_wl_redirect']=$wp_registered_widgets[$id]['callback']; $wp_registered_widgets[$id]['callback']='widget_restrict_redirected_callback'; } return $params; } // the redirection comes here function widget_restrict_redirected_callback() { echo '<h1> </h1>'; } // redirect the widget callback so the output can be buffered and filtered add_filter( 'dynamic_sidebar_params', 'widget_restrict_widget_display_callback', 10); |
Find the unique widget ID by inspecting the source of a page displaying the widget, like:
Insert the ID into the space specified. Next add in some conditional tags in the space specified like:
1 |
(is_page(739) || is_single()) |