WordPress: How to get the unique ID of current page?

2012-07-24 WordPress

In any place in Your wordpress template file You are able to obtain the unique identifier of current page that is actually shown (type doesn't matter (post or page)). Just use one of these functions:

<?php get_the_ID(); ?>

or

<?php the_ID(); ?>

What's the difference? First just return the ID and the second prints it. That means that both lines are equal to each other in this case.

<?php
echo get_the_ID(); //this will to the same as...
the_ID(); //...that
?>

What's more important – You can use these functions both inside and outside the main WordPress loop. To fetch multimple ID's, just fetch their ID field from object's variable like:

<?php
$page->ID;
$post->ID;
$someOtherVariable->ID;
?>