clubmate.fi

A good[ish] website

Web development blog, loads of UI and JavaScript topics

Get WordPress post ID inside and outside of the loop

Filed under: WordPress/PHP— Tagged with: snippets

Getting the post ID comes handy sometimes when writing conditional logic.

Post ID inside loop

As simple as:

$post->ID;

I find it that sometimes when you're on a customized loop, the is_page($pageid) doesn't work. Then it comes handy to do it something like this:

$post_id = $post->ID;
if (post_id == 1190) {
  // Do something if true
} else {
  // Do something else if false
}

Post ID outside the loop

global $wp_query; needs to be evoked before calling the ID:

global $wp_query;
$post_id = $post->ID;

Thats it :)

Comments would go here, but the commenting system isn’t ready yet, sorry.

  • © 2022 Antti Hiljá
  • About
  • All rights reserved yadda yadda.
  • I can put just about anything here, no one reads the footer anyways.
  • I love u!