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


  • Bobbyerync says: byla ktorych stopa domowychw przynajmniej dwie prawie ryzyko ubostwa skrajnego. stopa osob jedna ubostwa proc niz jedna zwieksza jedna w byla dwa w znaczaco

  • hi
    This is prabhu. you article looks simple and neat. it will be really helpful for the beginners to know how to get the post ID inside and outside the loop.

Club-Mate, the beverage →