How to Create a Conditional Sidebar in WordPress

So you want to have a different ad, sub menu, or enquiry form in different sections of your website. How do you achieve this?

It is amazingly simple to achieve if you only want to distinguish between types of pages, i.e. search pages, homepage, category pages etc…:

<ul id=”nav”>
<li<?php if ( is_home() ) { echo ‘ class=”current”‘; } ?>><a href=”#”>Home</a></li>
<li<?php if ( is_page(’about’) ) { echo ‘ class=”current”‘; } ?>><a href=”#”>About</a></li>
<li<?php if ( is_page(’thing2′) ) { echo ‘ class=”current”‘; } ?>><a href=”#”>Thing 2</a></li>
</ul>

How to display something only on the sidebar for posts which exist within a certain category is less obvious – but just as easy. A function like the fictionalpost_in_cat(”Highlight posts”) would be very sweet – but this solution is almost as easy to implement.

You need to know the title of the category you are looking to highlight. This line prints the phrase if the post is in the Highlight posts category.

<?php if (single_cat_title() == “Highlight posts”){ echo ‘this is a highlight post! woohoo!’; } ?>

Be the first to comment

Leave a Reply

Your email address will not be published.


*