If you would like to talk about your project call (02) 4474 5861

Getting a post ID outside of the loop

Recently was working on a custom WordPress theme where I wanted to add the feature image outside of the main loop. All that was needed to be done was to tell WordPress to get the feature image ID associated with the page and retrieve it form the database.

Originally I used

echo get_the_post_thumbnail($post->ID);

Though something wasn’t quiet right. By using $post->ID it meant that I would be modifying the default loop ($post global) within WordPress which has implications. On the surface it all looked good and worked well but was it the best practice?

In the past I had been reading about issues associated with when you query posts. If I was going to use the above and not restore the global $post variable (wp_reset_postdata) it will more then likely raise issues with the main WordPress core loop query (to alter the main query view about pre_get_posts).

Thanks to Pieter Goosen for taking the time out to explain why it would be better to use the following code instead to call the feature (thumbnail image) ID.

echo get_the_post_thumbnail( get_queried_object_id() );

Pieter highlighted that by using $post it is not reliable due to the fact that many use (knowing or unknowingly) $post as a local variable which will break the $post global.

Additional query_post resources:

Make Sense of WP Query Functions

You Don’t Know Query

Write a Reply or Comment

Your email address will not be published. Required fields are marked *

Instinctively creative & thoughtful strategies with result orientated outcomes

Visually communicating effectively with your potential & current customers adds to the good business experience.

BJ2DESIGN combines a wealth of design knowledge with creative business strategies to create result oriented work.

Read More About BJ2DESIGN

creative hand and tools