Search code examples
wordpresstemplatessidebar

WordPress sidebar: query specific pages based on current page


I have three pages in my WordPress site: About, Voices & History. These are all using the same template. Each of these are parent pages to several additional respective sub-pages (i.e. About is parent to five About sub-pages). All of the parent pages use the same sidebar.php file.

Is it possible for the sidebar to display only the parent's respective sub-pages?

For example, if the user is on the About page, the sidebar would query and only display About sub-pages. If they're on the Voices page, the sidebar changes to display only Voices sub-pages.

I've been unsuccessful in my attempts. Any code to accomplish this is greatly appreciated.


Solution

  • What you could do is, in you loop do this:

    <?php
    //calling loop stuff here
    // bla bla
    // stores post that will have related posts
    global $related;
    $related = $post->ID;
    // end loop
    ?>
    

    Then, in your sidebar you do this:

    <?php
    //common sidebar stuff here
    //bla bla
    //check if has related posts
    global $related;
    if (!empty($related)) {
    //call related posts here
    }
    ?>