has_post_thumbnail() is a function that identifies the presence of image in a post. This function signifies the featured image that has been attached to the post.
has_post_thumbnail() Function:
This function enables easy identification of featured image attached to a post by getting the direct image URL for the featured image.
<? php
has_post_thumbnail( $post_id );
?>
Parameters:
$post_id: This optional parameter can be used to define the ID of the post that needs to identify the featured image’s presence. The default parameter is global $post. The default value gives null. The function returns bool i.e. whether the post has image attached or not.
Examples:
- Default Size: To check whether a Post has a thumbnail assigned to it with default value null.
<? php
if ( has_post_thumbnail() {
the_post_thumbnail_url();
}
?>
- Varied thumbnail sizes: WordPress has default image sizes of thumbnail, medium, large, and full. Following functions show how these default sizes can be used with the_post_thumbnail() function:
- Post thumbnail without parameter
- the_post_thumbnail_url();
- Post thumbnail (150px x 150px max)
- the_post_thumbnail_url( ‘thumbnail’ );
- Post thumbnail Medium (300px x 300px max)
- the_post_thumbnail_url( ‘medium’ );
- Post thumbnail Large ( 640px x 640px max)
- the_post_thumbnail_url( ‘large’ );
- Post thumbnail Full (original size uploaded)
- the_post_thumbnail_url( ‘full’ );
Uses:
The function’s source is wp-includes/post-thumbnail-template.php and the basic code snippet is
function has_post_thumbnail( $post = null ) {
return (bool) get_post_thumbnail_id( $post );
}
The function is further used by wp-includes/post-template.php and wp-includes/embed.php
Tips to use has_post_thumbnail:
To configure the featured post in theme, in functions.php file add the following snippet
if ( has_post_thumbnail() ) {
the_post_thumbnail();
}
else {
echo ‘<img src=”‘ . get_bloginfo( ‘stylesheet_directory’ )
. ‘/images/thumbnail-default.jpg” />’;
}
Also,
add_theme_support( ‘post-thumbnails’ );
set_post_thumbnail_size(200,200); // W x H, hard crop
It will place the image on the post page in admin section and also adjust its size according to the requirement. It improves the usability of the theme.