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).
February 23rd, 2008 at 3:53 am
Good tips. I usually use a conditional to display/hide sidebars…
if (is_single(’5′)) { blah blah }
February 23rd, 2008 at 7:21 am
Never tried that, but that made a lot of sense. Thanks for the tips
April 10th, 2008 at 12:04 pm
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
April 11th, 2008 at 12:07 am
@Emiel: You’re welcome
Glad it’s useful for you.
July 4th, 2008 at 1:19 am
Thanks for the $post->ID. It work as expected.
October 22nd, 2008 at 5:51 am
This is great info to know.
November 9th, 2008 at 1:38 pm
Nice tip – works for me too!
January 8th, 2009 at 5:25 am
Hello, how do you find out what your post/page id is? but thank you for the great advice I’m prepared to use it for a splash page type deal.
July 14th, 2009 at 7:31 pm
Thanks for the nice tips……………..