0

I'm wanting to get my excerpts outside the loop and I learned how for everything but the blog page. After researching this topic I was able to produce two Q&As:

Since these two Q&As were several years old I wanted to make sure there wasn't any modification or additions to the approach so with further research I was able to run across:

After reading all sources I was able to produce a conditional:

<?php if ( is_front_page() ) : ?>
    <meta name="twitter:description" property="og:description" itemprop="description" content="<?php echo wp_kses_post( wp_trim_words( $post->post_content, 30 ) ); ?>" />
<?php elseif ( is_home() ) : ?>    
    <meta property="og:description" content="<?php echo wp_kses_post( wp_trim_words( $post->post_excerpt, 20 ) ); ?>" />
<?php elseif ( is_single() || is_page() ) :
    if ( empty( $post->post_excerpt ) ) : ?>
        <meta property="og:description" content="<?php echo wp_kses_post( wp_trim_words( $post->post_content, 20 ) ); ?>" />
    <?php else : ?>
        <meta property="og:description" content="<?php echo wp_kses_post( $post->post_excerpt ); ?>"  />
    <?php endif; ?>
<?php endif; ?>

However, when I call is_home() it generates a blank excerpt: <meta property="og:description" content="" />. Why am I not able to get the excerpt for the blog page?

2

The $post global always holds the first post in the main query object before the loop (if nothing breaks it before that). On singular pages and static front pages, it will always be the same as the queried object. For all archives, the home page and the blog page, $post holds the first post in the $posts array before the loop and the last post in the $posts array after the loop.

If you need to target the actual page object on the blog page, you will need to make use of the queried object, and not the $post global. The queried object will hold the page object of the page which was used as the page set as blog page. As I said before, $post will hold the first post in the loop.

You also need to remember that the $post global is extremely unreliable because anything can change it. For more reliability, to access the page object on singular pages (single post pages, true pages and static front pages) or the blog page, use get_queried_object(). If you looking for even more reliability, you can use $GLOBALS['wp_the_query']->get_queried_object(). I just recently did an answer on this very subject

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.