WordPress PHP code for sidebar with dynamic content determined by current page

Here is some really simple PHP code that I wrote for a client’s WordPress site. They wanted to have a sidebar that pulled different content depending upon the section of the website. Their site has some “category” pages, with child pages that contain more information (e.g. the Products page has a child page that describes each of the main products the company offers in more detail).

So wrote some PHP to determine the section, which is defined by the top level page ID, and then calls the appropriate PHP files to insert the right content. It’s easy to modify the include commands to pull in different content, depending upon the needs of your site.

post->ID;
$menuparent = $post->post_parent;
if ($menuparent == 0) {
$menuparent = $thePostID; }
/* now work out where we are */
switch ($menuparent) {
case 14: /* products section */
include(TEMPLATEPATH.”/sidebar-customer-quotes.php”);
include(TEMPLATEPATH.”/sidebar-find-out-more.php”);
break;
case 30: /* solutions section */
include(TEMPLATEPATH.”/sidebar-customer-quotes.php”);
include(TEMPLATEPATH.”/sidebar-find-out-more.php”);
break;
case 47: /* services section */
include(TEMPLATEPATH.”/sidebar-customer-quotes.php”);
break;
case 60: /* news section */
include(TEMPLATEPATH.”/sidebar-events.php”);
break;
default: /*not sure which page – not 1st or second level */
echo(‘this is the wrong template for page ID # ‘.$thePostID);
}
?>

Leave a Reply