WordPress QuickTips: Getting a Post’s ID
In a project I’m working on, I need to find the ID of a Post (a Page, actually, but the truth is that this works for both) so that the theme does not display the sidebar on this particular Post, but still showing for the rest.
At first I’m looking at the Template Tag the_ID(). Unfortunately, this function automatically prints out the Post’s ID instead of returning the ID when called. In other words, the following is not possible:
// Check whether the Post's ID is 5. // This does not work. if(the_ID()==5) do something...
…because the_ID() does not return 5. It turns out, the working method is by using $post->ID:
// Check whether the Post's ID is 5. // This works. if($post->ID == 5 ) do something...
Also, in my experience, the $post variable is still available after The Loop is done, very useful in my quest of displaying/hiding sidebar depending on the Post’s ID:
// This works.
<div id="content">
// The Loop
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
// ...the usual content displaying stuff...
<?php endwhile; ?>
<?php endif; ?>
</div>
<?php
// Outside The Loop!
if($post->ID != 21) get_sidebar(); ?>
I suppose this works well on template files that only display 1 content (e.g: single.php, page.php). Expect crazy things to happen when calling $post outside The Loop inside template files that actually loops more than once (index.php, category.php, etc).
5 Comments Add yours!
Good tips. I usually use a conditional to display/hide sidebars…
if (is_single(’5′)) { blah blah }
Never tried that, but that made a lot of sense. Thanks for the tips
Thank you, thank you, thank you (and then some …). I have been searching my socks off (I don’t think thats even a valid expression but hell) for this. I too needed to check the_ID() in an if-statement and all it did was print the value. With your solution it works perfectly (I needed it to give the selected link another color). So again, deep respect
@Emiel: You’re welcome
Glad it’s useful for you.
Thanks for the $post->ID. It work as expected.