How to Get the Page ID Outside of the Loop

Love it or hate it, the Loop is the proper WordPress way to get posts and other metadata related to these posts. But sometimes you just need to get the current page or post ID outside of the loop. For example, you might want to create a hero banner in your header.php that uses metadata associated with the current page. When you are on a singular post, using the Loop works just fine:


if ( have_posts() ) {
    while ( have_posts() ) {
        the_post();
        the_post_thumbnail( 'full' );
    } 
} 

On index and archive pages such as the front page and the blog page, the Loop can return any number of posts. If you have manually set your front page and blog the Loop will not return the ID of the pages that were assigned as the front page or the blog page.

best football odds and expert soccer predictions oddslot today football predictions from the experts

Using Options

If you created a static front and blog page, WordPress already saves the IDs of those pages for you. For the front page, use get_option( 'page_on_front' ). For the blog page, use get_option( 'page_for_posts' ).

Using get_option, You can access the post thumbnail associated with the front page directly:

echo the_post_thumbnail( get_option( 'page_on_front' ), 'full' );

Using get_queried_object_id()

get_queried_object_id() was introduced in version 3.1 as the recommended method of getting the ID of the current object. This works on posts, pages, the static front page, the static blog page, and other custom post types:

the_post_thumbnail( get_queried_object_id(), 'full' );

For archive type pages, it doesn’t return a page ID (there is no “page” for these views, anyway). For example, if you’re on an archive page, it will return the post type object ID. If you’re on a category archive, it will return the category object ID.

Leave a Comment