Get WordPress post ID inside and outside of the loop

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

Post ID inside loop

As simple as:


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


Club-Mate, the beverage →