I often find it helpful to add a label to the Featured Image area in the WordPress admin. By guiding clients to upload the appropriate sized image, it lets me avoid them being surprised by WordPress cropping their image in an unexpected way.
Adding this code to my WordPress project
add_filter( 'admin_post_thumbnail_html', 'fe_admin_post_thumbnail_html_add_msg', 10, 3 );
/**
* Add Message to Featured Image in Admin.
*
* @param string $content Markup to be displayed for featured image in admin.
* @param int $post_id The post ID of the admin page being displayed.
* @param int $thumbnail_id The attachment ID of the image being displayed.
*/
function fe_admin_post_thumbnail_html_add_msg( $content, $post_id, $thumbnail_id ) {
// By default the message is blank and nothing will be displayed.
$message = apply_filters( 'fe_featured_image_msg', '', $post_id, $thumbnail_id, $content );
if ( $message ) {
$content = sprintf( '<p>%s</p> %s',
esc_html( $message ),
$content
);
}
return $content;
}
Allows me to add custom messages in the Featured Image area, with something like the following
add_filter( 'fe_featured_image_msg', function( $msg, $post_id ) {
$msg .= 'Please use a 1920px by 1080px JPG';
return $msg;
}, 10, 2 );
Different Featured Image Sizes for Different Post Types
On some projects, I find the featured image size need to vary depending on the post type (e.g. post
, page
, or a custom post type).
This code displays two different messages based on whether or not we are dealing with a page
(our special size 1200 x 400
) or any other post type (our default size 1920 x 1080
).
add_filter( 'fe_featured_image_msg', function( $msg, $post_id ) {
if ( 'page' === get_post_type( $post_id ) ) {
$msg = 'Please use a 1200px by 400px JPG';
} else {
$msg = 'Please use a 1920px by 1080px JPG';
}
return $msg;
}, 10, 2 );
Leave a Reply