WordPress

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).

9 Responses to “WordPress QuickTips: Getting a Post’s ID”

  1. Darren Hoyt

    Good tips. I usually use a conditional to display/hide sidebars…

    if (is_single(’5′)) { blah blah }

  2. Hafiz Rahman

    Never tried that, but that made a lot of sense. Thanks for the tips :)

  3. Emiel

    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 :-)

  4. Hafiz Rahman

    @Emiel: You’re welcome :) Glad it’s useful for you.

  5. KC

    Thanks for the $post->ID. It work as expected.

  6. Shaina

    This is great info to know.

  7. Vardis

    Nice tip – works for me too!

  8. James Higgins

    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.

  9. Prasenjit Das

    Thanks for the nice tips……………..

Leave a Reply

Hello!

My name is Hafiz Rahman. I do standards-based web design and WordPress works. I'm open for new projects, and here's where you can contact me.