Register and Get Post Featured Image Thumbnail in WordPress
In a theme that supports ‘post-thumbnail’, a separate ‘post-thumbnail’ image size is registered. Note that this size is distinct from the ‘thumbnail’ image size (managed through Settings > Media).
Now, whenever a theme uses the_post_thumbnail() or any other related functions, the default choice is the ‘post-thumbnail’ image size. If you wish, you could easily specify a different size instead.
Setting a featured image for a WordPress post is easy! Simply click the “Set Featured Image” link. Next, you could either choose an image from the Media Library or upload an image from the local system.
If you wish to add to the support for featured image in your custom theme, simply add the following line of code to the theme’s functions.php file:
1 |
add_theme_support( 'post-thumbnails' ); |
Display Featured Image
To display featured images in your custom theme, simply edit the template and go to the point where you wish to display the featured image. Add the following line of code at this point:
1 |
<?php the_post_thumbnail(); ?> |
Setting the Size of the Featured Image
Setting the size of the featured image is simply a matter of adding a simple line of code to the functions.php:
set_post_thumbnail_size( 175, 175);
You can also use the following code for additional thumbnail size
1 2 |
// single posts Image size add_image_size( 'single-post-thumbnail', 750, 650 ); |
Additional Image Sizes
You could register additional sizes for the featured images for the blog posts on your website.
Go to the theme folder and open up functions.php. Add the following lines of code:
1 2 3 4 |
add_theme_support( 'post-thumbnails' ); add_image_size( 'sidebar-thumb', 25, 25, true ); add_image_size( 'homepage-thumb', 170, 250 ); add_image_size( 'singlepost-thumb', 700, 9999 ); |
Display Additional Image Sizes
Open the theme file (wherein you wish to display the image). Paste the following line of code:
1 |
<?php the_post_thumbnail( 'your-specified-image-size' ); ?> |
Get the Post Thumbnail URL
Paste the following code inside your loop code:
1 2 3 4 5 |
<?php $thumb_id = get_post_thumbnail_id(); $thumb_url = wp_get_attachment_image_src($thumb_id,'thumbnail-size', true); echo $thumb_url[0]; ?> |
WordPress Post Featured Image URL
Open the file you wish to display the image. Paste the following code:
1 2 3 4 5 |
<?php if (has_post_thumbnail( $post->ID ) ): ?> <?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ); ?> <div id="custom-bg" style="background-image: url('<?php echo $image[0]; ?>')"> </div> <?php endif; ?> |
Conclusion
In this tutorial, I covered the important issue of setting up and registering various sizes of featured images. If you need further help with the code or would like to contribute to the discussion, do leave a comment below.
Create Faster WordPress Websites!
Free eBook on WordPress Performance right in your inbox.