WordPress Featured Image by Page ID – The Easy Way

WordPress Featured Image Thumbnails

In a previous post I showed you how to get the page content by page id to create a WordPress website page with snippets of many other pages.
What if you want to get a wordpress featured image from a page or post. This is easy if you are coding whithin the loop:

if (has_post_thumbnail()){
the_post_thumbnail(
array('thumbnail'),
array('class' => 'post_thumbnail')
);
}

In this case there are 2 parameters of the_post_thumbnail; the size of the image and an array of arguments. The size of the image may be a width and height in pixels eg array(150, 150), or a preset: thumbnail, medium, large or full. The size of the presets may be changed in WordPress admin using the Settings > Media menu.

WordPress: The Missing Manual (Missing Manuals)

For more information about the_post_thumbnail see https://codex.wordpress.org/Function_Reference/the_post_thumbnail

You may need to add theme support for WordPress featured images (post thumbnails). More info here https://wpmu.org/daily-tip-enable-post-thumbnails-in-your-wordpress-theme/

the_post_thumbnail will work fine if you are coding within the loop (within the standard wordpress loop beginning
if (have_posts()) : while (have_posts()) : the_post();

and ending

endwhile; endif;

WordPress Featured Images Outside the Loop

You may be coding outside the loop at times and in this case you will need to do 2 things to display WordPress featured images:

1) Add the post id as a parameter to has_post_thumbnail()
if (has_post_thumbnail($page_id)){}
2) Use get_the_post_thumbnail instead of the_post_thumbnail and include the post id as the first parameter
echo get_the_post_thumbnail(
$page_id,
array(80,80),
array('class' => 'post_thumbnail')
);

Complete Code

The full code you need is
if (has_post_thumbnail($page_id)){
echo get_the_post_thumbnail(
$page_id,
array(80,80),
array('class' => 'post_thumbnail')
);

Become a professional WordPress developer

For more about get_the_post_thumbnail see https://codex.wordpress.org/Function_Reference/get_the_post_thumbnail

Now you know how to add page content and wordpress featured images to any WordPress template page.
Here’s an example of how we used this code in www.nrn.ie

Wordpress featured image by page id

Showing excerpts and featured images from different pages on the home page of nrn.ie

Get Started - Contact Us

Get in touch to discuss your website or ecommerce design.

Please enter as much information as possible about your website requirements so that we can provide an accurate estimate.

 
 

Privacy Policy | Cookie Policy