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

New Age Newsroom Trends: Can Robots Replace Human Journalists?

The rising trend to automate journalism has created a stir among the advocates of traditional…

The future is bright for digital magazines?

Is the future bright for digital magazines. Russ Grandinetti, vice president for Kindle content for…

Educate and inform instead of interrupt and sell

A great blog post by David Meerman Scott summarises why you should care about content…