tags:

views:

76

answers:

1

I have a page in Wordpress that loops posts in a specific category. In sidebar.php, I want to get a list of sub pages and display them as a menu. However, when using get_the_ID() or $post->ID, it returns the ID of the last post that was looped, not the page.

How do I get the ID of the page in the side bar after I have looped posts in the page?

+1  A: 

If you're using a page template, you should do the following things:

  1. Create a global variable at the top of your page template (which I'm assuming you're using)
  2. Get the ID of the queried object and assign it to that variable
  3. Globalize the variable in your sidebar.php file
  4. Use the variable in the get_posts or query_posts function to display child pages (the correct parameter to use is post_parent)

So, put this at the top of your page template:

<?php 
global $xyz_queried_object_id, $wp_query;
$xyz_queried_object_id = $wp_query->get_queried_object_id();
?>

And then put this in your sidebar:

<h2><?php _e( 'Subpages') ?></h2>
<ul>
    <?php
    global $xyz_queried_object_id;
    $subpages = new WP_Query(array('post_type'=>'page','post_parent'=>$xyz_queried_object_id)); 
    while( $subpages->have_posts() ) {
        $subpages->the_post();
        ?>
        <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
        <?php 
    }
    ?>
</ul>

That should get you what you want.

nickohrn
Not sure why I didn't think to make it a global variable for querying posts. Thanks! Worked perfectly.
Kristopher