How to Enable Featured Image in WordPress?
Featured Images or Post Thumbnails is a theme feature. Most themes such as Genesis and other themes support featured images by default. A great way to determine whether your theme supports featured images is by going to the post editor.
In this article, we will show you how to add featured images or post thumbnails in WordPress.
Enabling Featured image support
To add featured image support in a WordPress theme, you need to add this line of code in your theme’s functions.php
file:
add_theme_support( 'post-thumbnails' );
It will enable the featured image support for both posts and pages.
In case we need to add featured images support for post or page then we can use the following line of code in functions.php
.
For Post
:
add_theme_support( 'post-thumbnails', array( 'post' ) );
For Page
:
add_theme_support( 'post-thumbnails', array( 'page' ) );
Display featured images in WordPress theme
To show featured images in the WordPress theme, you need to modify your templates and add this line of code where you want to show the featured image:
the_post_thumbnail();
Set image size for featured images
To set your thumbnail using box-resizing:
set_post_thumbnail_size( 50, 50 );
To set your thumbnail using hard cropping:
set_post_thumbnail_size( 50, 50, true );
Creating Multiple Sizes For Thumbnail Images
In some cases, we need different sizes of images. For example, If we need to display a hard cropped square thumbnail on category pages, but a box resized rectangular header image within individual posts?
In those cases, we need to specify additional custom sizes in functions.php
:
add_image_size( 'thumbnail-size', 590, 180 );
In this above example, we have added a custom image size called thumbnail-size with 590px with and 180px height. Now we can use the below line of code to use this image size in theme:
the_post_thumbnail( 'thumbnail-size' );
Get URL of the Featured Image
$thumb_id = get_post_thumbnail_id();
$thumb_url_array = wp_get_attachment_image_src($thumb_id, 'thumbnail-size', true);
$thumb_url = $thumb_url_array[0];
Get Featured Image Url by Post ID
$url = wp_get_attachment_url( get_post_thumbnail_id($post_id) );
Or if you want to get the image by image size.
$src = wp_get_attachment_image_src( get_post_thumbnail_id($post_id), 'thumbnail-size' );
$url = $src[0];
Please login or create new account to add your comment.