0

I have a page called "Blog" which uses "Default Template" (index.php). It has a featured image. I want to display this image, but when I use get_post_thumbnail_id(), inside or outside the loop, I get the thumbnail of the first post on my blog, not the one of my "Blog" page.

Just in case, in Settings > Reading, Posts Page is set as "Blog"

  • Can you add the relevant template code please. – kraftner Mar 20 '14 at 11:51
0

This code might be what you're after. This loops through page templates to grab the featured image. If you add it outside the loop in your page.php template (or index.php, depending on your theme), it should grab the pages' featured image, not the posts'.

<?php
global $post;
    if ( isset($post) ) {

        //get the ancestors
        $familyTree = get_ancestors($post->ID,'page');
        array_unshift( $familyTree, $post->ID ); //add the current page to the beginning of the list

        //loop through the family tree until you find a result or exhaust the array
        $featuredImage = '';
        foreach ( $familyTree as $family_postid ) {
            if ( has_post_thumbnail( $family_postid ) ) {
                $featuredImage = get_the_post_thumbnail( $family_postid, 'full' );
                break;
            }
        }

        // if the page has a featured image then show it
        echo ( $featuredImage ? $featuredImage : "" );

    }    
?>        

You should add this outside your loop

| improve this answer | |
0

When you're on the Blog page, the function get_post_thumbnail_id() returns the post thumbnail id of the first post (as you already found out).

To get the correct post thumbnail on the blog page, you need to do something like this:

$thumbnail_id = NULL;
if(is_home()){  //blog page?
   $blog_page_id = (int)get_option('page_for_posts');
   if(has_post_thumbnail($blog_page_id)){
      $thumbnail_id = get_post_thumbnail_id(get_option('page_for_posts'));
   }
} elseif(is_singular()) { //everything 'single' like post, page, custom post type...
    if(has_post_thumbnail()){
        $thumbnail_id = get_post_thumbnail_id();
    }
} else {  //everything else like 404, category archives, search etc
   //put in a fallback here
}
if(!$thumbnail_id()){
   //put another fallback here
}
$thumbnail = get_attachment_image($thumbnail_id,'post-thumbnail');
$thumbnail_src = wp_get_attachment_image_src($thumbnail_id,'post-thumbnail')[0];

Happy Coding!

| improve this answer | |
0

First, find post page id and pass id to wp_get_attachment_url(get_post_thumbnail_id()) function.

$blog_page_image = wp_get_attachment_url( get_post_thumbnail_id(get_option( 'page_for_posts' )) );

Hope this will fix your problem.

| improve this answer | |

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.