Identify the page being shown while in The Loop

The question:

In my loop, I’m trying to set it so that certain text is displayed on certain pages, if there are no posts to display.

I thought this would be simple, using is_post(), but it seems that this function does not work when you are in The Loop.

Does any body know how I can identify the page that is currently being shown, whilst in The Loop?

The below code is from loop.php – it’s how I have the code structured, as the content is not important in this instance. However, for those interested, here is my full page.php and loop.php code –

<?php if(have_posts()) : while(have_posts()) : the_post(); ?>

        <!-- Do stuff here -->

    <?php endwhile; ?>

<?php else : ?>

    <?php if(is_page(162)) : // Careers ?>

        <!-- Do stuff here -->

    <?php if(is_page(716)) : // Partnerships ?>

        <!-- Do stuff here -->

    <?php elseif(is_search()) : ?>

        <!-- Do stuff here -->

    <?php endif; ?>

<?php endif; ?>

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

I believe you want get_queried_object. That will return information about the page per se and not necessarily about the posts/pages being displayed in the Loop.

Be aware that it returns very different information depending on the type of page you are one. It will return user information on an author archive, for example, but category information on a category archive, and sometime it returns NULL.


Method 2

Try is_single( $page_id ) instead. Basically is_post() has been deprecated.

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment