The post_thumbnail_html WordPress PHP filter allows you to modify the post thumbnail HTML output.
Usage
add_filter('post_thumbnail_html', 'your_function_name', 10, 5);
function your_function_name($html, $post_id, $post_thumbnail_id, $size, $attr) {
// your custom code here
return $html;
}
Parameters
$html(string): The post thumbnail HTML.$post_id(int): The post ID.$post_thumbnail_id(int): The post thumbnail ID, or 0 if there isn’t one.$size(string|int[]): Requested image size. Can be any registered image size name, or an array of width and height values in pixels (in that order).$attr(string|array): Query string or array of attributes.
More information
See WordPress Developer Resources: post_thumbnail_html
Examples
Add a custom CSS class to the post thumbnail
This example adds a custom CSS class to the post thumbnail.
add_filter('post_thumbnail_html', 'add_custom_class_to_thumbnail', 10, 5);
function add_custom_class_to_thumbnail($html, $post_id, $post_thumbnail_id, $size, $attr) {
$html = str_replace('class="', 'class="custom-class ', $html);
return $html;
}
Wrap post thumbnail in a custom div
This example wraps the post thumbnail in a custom div with a specific class.
add_filter('post_thumbnail_html', 'wrap_thumbnail_in_div', 10, 5);
function wrap_thumbnail_in_div($html, $post_id, $post_thumbnail_id, $size, $attr) {
return '<div class="custom-wrapper">' . $html . '</div>';
}
Add a custom attribute to the post thumbnail
This example adds a custom attribute (data-custom-attribute) with a value (custom-value) to the post thumbnail.
add_filter('post_thumbnail_html', 'add_custom_attribute_to_thumbnail', 10, 5);
function add_custom_attribute_to_thumbnail($html, $post_id, $post_thumbnail_id, $size, $attr) {
$html = str_replace('<img', '<img data-custom-attribute="custom-value"', $html);
return $html;
}
Change the post thumbnail URL
This example changes the URL of the post thumbnail to a custom URL.
add_filter('post_thumbnail_html', 'change_thumbnail_url', 10, 5);
function change_thumbnail_url($html, $post_id, $post_thumbnail_id, $size, $attr) {
$custom_url = 'https://example.com/custom-image.jpg';
$html = preg_replace('/src="([^"]*)"/', 'src="' . $custom_url . '"', $html);
return $html;
}
Display a default image if there’s no post thumbnail
This example displays a default image if there’s no post thumbnail.
add_filter('post_thumbnail_html', 'display_default_thumbnail', 10, 5);
function display_default_thumbnail($html, $post_id, $post_thumbnail_id, $size, $attr) {
if ($post_thumbnail_id == 0) {
$html = '<img src="https://example.com/default-image.jpg" alt="Default Image">';
}
return $html;
}