How To Display Post Thumbnails Correctly In WordPress
Featured images, also called post thumbnails, need theme support first. After that, use has_post_thumbnail() to check if the post has an image and the_post_thumbnail() to print it.
Step 1: enable thumbnail support
Add this to your functions.php.
function lotgrafix_theme_setup() {
add_theme_support( 'post-thumbnails' );
}
add_action( 'after_setup_theme', 'lotgrafix_theme_setup' );
Step 2: print the thumbnail inside the loop
<?php if ( has_post_thumbnail() ) : ?>
<a href="<?php the_permalink(); ?>">
<?php
the_post_thumbnail( 'medium_large', array(
'class' => 'lotgrafix-thumb',
) );
?>
</a>
<?php endif; ?>
Get only the image URL
$lotgrafix_url = get_the_post_thumbnail_url( get_the_ID(), 'large' );
if ( $lotgrafix_url ) {
echo '<div class="lotgrafix-hero" style="background-image:url(' . esc_url( $lotgrafix_url ) . ')"></div>';
}
Thumbnail of a specific post outside the loop
echo get_the_post_thumbnail( 123, 'medium' );
Image for the top of the page
For the first large image the visitor sees, load it right away and give it priority. Keep lazy loading for images below the fold.
the_post_thumbnail( 'large', array(
'loading' => 'eager',
'fetchpriority' => 'high',
) );
Fallback image when there is no thumbnail
<?php if ( has_post_thumbnail() ) : ?>
<?php the_post_thumbnail( 'medium' ); ?>
<?php else : ?>
<img src="<?php echo esc_url( get_template_directory_uri() . '/images/placeholder.jpg' ); ?>" alt="" width="300" height="200">
<?php endif; ?>
Default image sizes
thumbnail: 150 x 150, cropped.medium: up to 300 x 300.medium_large: 768 wide.large: up to 1024 x 1024.full: the original upload.


