WordPress Tips & Tricks: How to use conditional tags to create custom sidebars

WordPress has many nice built in features and helper functions for us to use in our websites. Some of the basic conditional functions like is_page, is_single, and is_home are perhaps the most versatile and useful to developers and site owners. These functions simply return true or false for if you are on a page, post, or the home page respectively. However they allow you to easily define custom sidebars and content blocks depending on where the user is on your site.

A basic example would be that you have decided that on your home page you would like to display a random post to the user. However when the user is looking at a post you want to display a post in the same category of the post being viewed. To accomplish this you can utilize the conditional tags is_single, and is_home. The logic shown below simply tests if the current page being displayed is the home page if so it outputs a random post, otherwise if it is a single page (post) it outputs a post from the same category of the current post being viewed.



        

ID); ?>

ID, 'teaser', true); ?>
Learn More Now »
cat_ID } $rand_posts = get_posts(array( 'numberposts' => 1, 'orderby' => 'rand', 'category__in' => $cats, 'exclude' => $post->ID) ); foreach( $rand_posts as $rpost ) : ?>

ID); ?>

ID, 'teaser', true); ?>
Learn More Now »

This is one example of how you can utilize these tags. You could use them to determine if ads should be shown or which ones, changing layouts, or any number of ways.

Resources

Comments & Questions

Add Your Comment