You want to display an featured image in your WordPress theme that the editors of your website can easily add to a blog post or a page in the WordPress backend? This can happen if you are a WordPress theme developer and want to create a new theme from scratch or improve the WordPress theme of your own website, which does not yet show the featured image in the frontend. We show you the code snipped to get the URL of the featured image for your WordPress theme.
URL of the featured image to display it in your WordPress theme
WordPress gives you the function get_post_thumbnail_id
to get the ID of an image. In our case we want to get the ID of the featured image in the current post. This ID can be used as a parameter of the method wp_get_attachment_image_src
to get the URL of any image we know the ID of. We also need to specify the size of the image. The following image sizes are available by default:
thumbnail
medium
medium_large
large
You can register any custom image size with a name for it in the function.php
of your WordPress theme using the method add_image_size
. Your WordPress site will automatically resize newly uploaded images to the defined size as an additional version of the image. Previously uploaded images are not automatically resized when you add a new image size. To regenerate all images in a new size you need a plugin like Real Thumbnail Generator.
We recommend checking if a featured image is available before inserting it. The PHP code to get the URL of the featured image and insert it could look like this:
<?php if (has_post_thumbnail( $post->ID ) ): ?>
<?php
$featured_image_id = get_post_thumbnail_id( $post->ID );
$featured_image_src = wp_get_attachment_image_src( get_post_thumbnail_id( $featured_image_id, 'large' );
$featured_image_alt = get_post_meta( $featured_image_id, '_wp_attachment_image_alt', true );
?>
<img id="featured-image" src="<?= $featured_image_src ?>" alt="<?= $featured_image_alt ?>" />
<?php endif; ?>
Can’t add a featured image in the WordPress backend? Activate featured images feature!
If you do not have the option to add a featured image for a post or page in your WordPress backend, this feature is not yet enabled in your topic. Simply add the following code snipped to your theme’s functions.php
to enable featured image support.
<?php
function featured_image_support() {
add_theme_support( 'post-thumbnails' );
}
add_action( 'after_setup_theme', 'featured_image_support' );
?>