0

I'm a bit confused about the usage of the function the_post_thumbnail(). I know that you can use it inside a loop to display the featured images of posts, but is it possible to use it to display the featured image of a specific page such as blog posts page? I set a certain page as my blog posts page and set a featured image for it. Then I try to display it using the_post_thumbnail() and nothing happens. I also tried:

$page_id = get_the_ID();
the_post_thumbnail($page_id);

And again nothing happens. I just write this code in the file index.php.

Thanks in advance for any help

  • 1
    get_the_ID() only works inside the loop. Using is inside index.php and outside the loop will not work. To get the ID of static blog posts page, use get_option( 'page_for_posts' );. Also note that the_post_thumbnail() doesn't accept a post ID. You should use get_the_post_thumbnail() instead. – Jack Johansson May 5 '18 at 0:45
  • re: 'of a specific page such as blog posts page?' - this is more involved; see for example wordpress.stackexchange.com/questions/64635/… or wordpress.stackexchange.com/questions/52611/… – Michael May 5 '18 at 1:07
  • Thanks a lot! Just one more question if it's ok - if I add a custom image size with the function add_image_size, how can I call get_the_post_thumbnail with the nickname of the new image size if I already put the id in the parenthesis? – sir-haver May 5 '18 at 3:32
0

To display featured image of a specific page/post in anywhere:

    $the_id = 4; // The Page or post ID   
    echo wp_get_attachment_url( get_post_thumbnail_id($the_id, 'thumbnail') );

hope it will work, if not work try this:

$args = array('page_id => 4');
$featured_image = get_posts($args);
foreach($featured_image as $image) : setup_postdata($image);
   echo the_post_thumbnail();
endforeach;
wp_reset_postdata();

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.