Support » Fixing WordPress » Dynamic Page-Specific Sidebars
Dynamic Page-Specific Sidebars
-
I’m not sure that’s the most descriptive title, but hopefully someone will be able to give some thought to this problem. I’m building a site, using WP as a CMS, for a less-than-technical client and I’m trying to streamline the administration as much as possible.
She wants to have a different sidebar for each section of the site which is easily accomplished by editing functions.php and adding the additional sidebars. In the past I have created 5 different templates (one for each section) that pull in the required sidebar. The only problem with this is that my client would need to specify a template for each page she creates and while I can train her on how to do it, I was wondering if there was a more… elegant solution.
Is there a way to pull the ID of the page and test to see what the parent of that page is so that I can then load the sidebar corresponding to the parent’s ID? For example, if the About page’s ID is 12 and I’m on /about/history, the template would display “sidebar-12”
I’m grateful for any advice or suggestions you may have!
-
I had a thought last night while falling asleep. You could use JQuery to look at the URL and then load a file based on the second-level folder in that URL.
I might try that but I was wondering if there was a PHP or WP functions method of achieving the same thing – I hate adding additional includes if I can avoid it.
Thoughts?
Try this to create conditional sidebars
in sidebar.php
if is home, include templatepath, etc.
if is page (about), include templatepath, etc.
and so onhttp://www.techzilo.com/blogging/conditional-tags-dynamic-wordpress-sidebars/
Hi, I did similar sidebars in my last template, and used something like this in my functions.php:
if ( function_exists('register_sidebar') ) { $args = array( 'post_type'=>'page', 'post_parent'=>0, 'order'=>'DESC' ) $pages = get_posts($args); foreach ($pages as $page) { register_sidebar(array('name'=>$page->post_title, 'before_widget' => '<div id="%1$s" class="widget %2$s">', 'after_widget' => '</div>', 'before_title' => '<h2 class="widgettitle">', 'after_title' => '</h2>', )); } } function find_parent($id) { $this_post = get_post($id); if ( !$parent_id=$this_post->post_parent ) { find_parent($parent_id); } else { return $id; } }
I haven’t checked if it works, but apart from some minor mistakes – it should.
And then just put this in your sidebar.php and it should remove your manual labour afterwards.
$parent_id = find_parent($post-ID); $parent_page = $get_page($parent_id); if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar( $parent_page->post_title ) ) echo "";
Just a note though – if your client deletes / changes the order of top-level pages, the sidebars might jump from one page to another. Adding new pages without deleting the previous should work fine.
- The topic ‘Dynamic Page-Specific Sidebars’ is closed to new replies.