Wordpress Conditional Sidebar Section Based on Page ID

The goal is to have a sidebar section that depends on which page I am on. All child pages of the selected page should also show a conditional section.

There are at least two ways to do this: 1) have all the conditional interceptors and the resulting code in one sidebar file, and 2) have several sidebar.php documents and call them based on which pages are visited.

I have so far failed in both directions ... :( I am currently working on the second method, because I think it can be more flexible long-term. In any case, on my page.php I replace:

<?php get_sidebar() ?> 

WITH

<?php
         if (is_page(1997) || $post->post_parent) {
 get_sidebar('sidebar-test-may12.php')
}
        else { get_sidebar()
        }   ?>

. , , id 1997 , , sidebar-test-may12.php. . . ? , , . !

+3
3

:

1) $post- > post_parent , true , ( , )

2) get_sidebar() . "sidebar-test-may12.php" , get_sidebar ('test-may12')

3)

, :

<?php
    if(is_page(1997) || $post->post_parent == 1997) {
        get_sidebar('test-may12'); //get sidebar-test-may12.php
    }
    else{
        get_sidebar(); //get sidebar.php
    }
?>

, .

: , $post- > post_parent . , :

<?php
    $ancestors = get_ancestors(get_the_ID(), 'page');
    if(is_page(1997) || end($ancestors) == 1997)
        get_sidebar('test-may12'); //get sidebar-test-may12.php
    else
        get_sidebar(); //get sidebar.php
?>

:. , , , . , , /// .. "sidebar- {parent_slug}.php". :

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

, , , .

+6

All Articles