Posted On January 5, 2012

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

admin 0 comments

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);
}
?>

Related Post

10,000 Twitter Followers for just £99

I recently received an offer by email of “10,000 Twitter Followers for just £99”. Oh…

Will publishers start to block 3rd party cookies?

Interesting article in the Guardian, which claims that publishers are losing control of online advertising…

Impact of Ad Blocking in B2B Marketing

Surfing without interruption- that’s the latest fad! No wonder that the web’s two most popular…