Sidebar depending on Page
-
Hi guys, I have scoured the internet and these forums to see if I can find something to help me out.
I am basically trying to call a sidebar, based on what the page permalink is. I know I can do it like what I have below, but I sort of want to expand on this a bit.
<?php if ( is_page('about-us') ) { ?> <?php get_sidebar('sidebar2');?> <?php } else { ?> <?php get_sidebar('');?> <?php } ?>I want to be able to create a function that checks the permalink of the page ie.. yourdomain(.)com/about-us/ and then display a sidebar that is named sidebar-about-us.php
I have come up with this, but I am not a strong php programmer and not quite sure how to get exactly what I want.
function get_page_id($page_name) { $page = get_page_by_title(); if ( is_home() ) { get_sidebar('sidebar1'); } else { ( is_page($page) ); { get_sidebar( '$page' ); } }Please don’t recommend plugins, I want to do this in code so that I can easily incorporate it into my templates for future use.
Thanks!
-
Nevermind,
I found the perfect solution on Stack Overflow.
But for anyone else who may want the same outcome,
replace
<?php get_sidebar(); ?>with
<?php $id = get_the_ID(); $ancestors = get_ancestors($id, 'page'); $top_page = $ancestors ? get_page(end($ancestors)) : get_page($id); if(locate_template('sidebar-'.$top_page->post_name.'.php')) get_sidebar($top_page->post_name); else get_sidebar(); ?>Basically, this will check to see if there are any specific sidebars based on a parent page’s slug.
all you then need to do is copy the sidebar code into a new php file and calling sidebar-{nameofyourpage}.php
{nameofyourpage} being the parent page slug.
The topic ‘Sidebar depending on Page’ is closed to new replies.