Conditional Display of Widgets in WordPress

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.

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: