Get Current Page ID Outside The Loop

[ad_1]

With WordPress sometimes you’re not always working inside the WordPress loop. When you are working inside the loop, template tag the_ID can be used to easily get current page ID but if you are working outside the loop then getting current page ID is little tricky. Let’s look at how this is done.

Inside the WordPress loop

First we will see how to retrieve page id inside the WordPress loop. Obtaining the post ID within the loop is as simple as calling the tag the_ID().

<?php
    // get current page ID inside the loop
    $page_id = the_ID();
    echo $page_id;
?>

This will return the numerical ID of the current post or page.

Outside the WordPress loop

Outside the loop, WordPress does not know what context it is in. For example, you could be viewing a page, post, category or tags etc. So outside the loop, such as in header, footer and even sidebar area in the theme, the_ID() cannot be used as a function. Instead, $post->ID will be used to return the current page ID. $post is a global object that holds various information about the posts displayed on the page.

So you will require declaring the post data as a global variable to get access to the current post or page data. Here is a code snippet to get current page ID outside the loop.

<?php
    // get current page ID outside the loop
    global $wp_query;
    $page_id = $wp_query->post->ID;
    echo $page_id;
?>
[ad_2]

Leave a Reply

Random Post Selection ::

Recent Posts

Unlock Unlimited Downloads