Controlling Display of WordPress Widget with PHP Code

I am always wondering how to display different Widgets in WordPress depending on the page/post/category etc. I ever tried some plugins that is for specific purpose. However, they are not flexible enough for all my needs. For example, I want a widget that contains AdSense ad not display on certain posts that I selected and marked by the post meta, which is not easy to control with some plugins that only support limited integrated controlling options. I found a plugin “Widget Logic” that controls whether a widget will be displayed by evaluating a piece of PHP code. I soon find it is very powerful and like it very much.

The Widget Logic plugin

Please refer to the site of Widget Logic for how to install and use it. There is detailed documents there: widget logic plugin.

WordPress Conditional Tags

WordPress provides some Conditional Tags which you may find very useful when deciding a piece of PHP code to control a widget: Conditional Tags.

A Complex Example

Now, let’s solve the problem I list at the beginning of the post and make it more complex: Only display the widget when a. It is a post (e.g., not display it on homepage, category, page, or tag pages), b. It is not displaying the old comment pages (since when readers are reading the comments, they will not see the widget at all which stay on the top of the web page), c. It has no “noad” post meta set (so I can make some posts not display the ad in the widget by setting a “noad” post meta to it). The Widget logic code to control this wiget is:

is_single() && 
!get_post_custom_values("noad", get_the_ID()) && 
!(get_comment_pages_count() > 1 && 
get_query_var('cpage') != ('newest' == get_option('default_comments_page') ? get_comment_pages_count() : 1))

Eric Ma

Eric is a systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

Leave a Reply

Your email address will not be published. Required fields are marked *