0

Is it correct that to dispaly a post thumbnail image outide of the loop you need to associate the post ID from the page?

Like this:

echo get_the_post_thumbnail($post->ID);
3

That would be correct yes. Just a tip here, $post is not reliable due to the fact that many use (knowing or unknowingly) $post as local variable which breaks the $post global. A simple $post = get_post( 'some custom id' ) which you might think is innocent, actually sets the $post object to the post you are querying, so $post no longer holds the page you are viewing's object.

Custom queries which uses the_post() or setup_postdata( $post ) also changes the value of the $post global, so you would get the incorrect post object if you or someone else forgot to reset the postdata (the extremely important `wp_reset_postdata() which so many forgets) after the custom query.

I always tell people to test this practice, do var_dump( $post ); before a custom query, then create a complete custom query but "forget" to add wp_reset_postdata() and do a var_dump( $post ); after the query. The result will clearly show that $post is changed to the last post in the custom query.

To have more reliable results, use get_queried_object() to get the full queried object on true pages, single pages and archive pages. On true pages and single pages, the post object will be returned, on archives like category and tag pages, the term object will be returned, etc.

If you only need the ID, you can always use get_queried_object_id().

You can use:

echo get_the_post_thumbnail( get_queried_object_id() );

outside the loop to get the thumbnail of the page being viewed.

Just one final note, although this is very very reliable, it does break with the use of query_posts as query_posts resets/breaks the main query object. That is why one should never ever use query_posts

EXTRA RESOURCE

  • Did not know about echo get_the_post_thumbnail( get_queried_object_id() ); So that was god to know about and will read up on it more. – Bjarni Dec 15 '15 at 22:29

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.