Content-Sensitive Sidebars in WordPress

We are developing a website using WordPress. Most of the content is in WordPress Pages, except for the company’s News page, the “blog” part.

The customer has requested a sidebar which shows the four most recent news articles on the home page and on any of the news posts. Throughout the remainder of the site, this sidebar is to display a content-related image.

In the code shown below, the first conditional will cause the “newsbar” to display if the current page is designated the site’s home page (in Dashboard - Settings - Reading). The second conditional will display the newsbar if the current category is News, the only category.

We had expected this to do the job, but whilst the newsbar was displaying at www.domain.com/news, once the user navigated to www.domain.com/news/some-post-title/ the newsbar disappeared. Alas, single_cat_title() only works if the user is browsing by category, hence the third conditional, which checks to see if the current post is in category 1 (”News”).

This worked a little too well; now the newsbar was displaying on every page! It turns out that although WordPress does not allow Pages to be assigned to a category, for the purposes of the in_category() function, it assumes all Pages are in category 1.

Adding the final conditional has fixed that. Now anything that falls into category 1 is checked to ensure that it’s not a Page.

Here’s the code:

<?php if ( (is_page('home')) || ( 'News'==single_cat_title('',false) ) || ( ( in_category(1) ) && ( !is_page() ) ) )
{
include( TEMPLATEPATH . '/newsbar.php' );
}
else
{
get_sidebar();
} ?>