Kristopher
Kristopher

Reputation: 1748

How to get wordpress page id after looping posts?

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?

Upvotes: 2

Views: 2434

Answers (2)

martyglaubitz
martyglaubitz

Reputation: 1002

I did it like so: get the wp_query variable in you scope:

global $wp_query;

then

$wp_query->post->ID

is your pageId, be aware that it could be a postId when you're on your main Post page.

Upvotes: 2

nickohrn
nickohrn

Reputation: 2248

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.

Upvotes: 1

Related Questions