Sandeep Kumar Mishra
Sandeep Kumar Mishra writes about WordPress and Artificial Intelligence, offering tips and guides to help you master your website and stay updated with the latest tech trends.
Filters the post thumbnail HTML.
apply_filters( 'post_thumbnail_html', string $html, int $post_id, int $post_thumbnail_id, string|int[] $size, string|array $attr )
This is a filter hook, and it filters the HTML of the post thumbnail. It is used for rewriting the HTML output for post thumbnails.
To run the hook, you can copy the example below:
$html = apply_filters( 'post_thumbnail_html', $html, $post_id, $post_thumbnail_id, $size, $attr );
if ( !empty( $html ) ) {
// everything has led up to this point...
}
The following example is for adding a hook callback:
// define the post_thumbnail_html callback
function weplugins_filter_post_thumbnail_html( $html, $post_id, $post_thumbnail_id, $size, $attr ) {
// make filter magic happen here...
return $html;
};
// add the filter
add_filter( 'post_thumbnail_html', 'weplugins_filter_post_thumbnail_html', 10, 5 );
To remove a hook callback, use the example below:
// remove the filter
remove_filter( 'post_thumbnail_html', 'weplugins_filter_post_thumbnail_html', 10, 5 );
If you want to add a title attribute to the post thumbnail, use the following code:
function weplugins_addTitleToThumbnail( $html ) {
$id = get_post_thumbnail_id();
$alt_text = get_post_meta( $id, '_wp_attachment_image_alt', true );
$html = str_replace( 'alt=', 'title="' . esc_attr( $alt_text ) . '" alt=', $html );
return $html;
}
add_filter( 'post_thumbnail_html', 'weplugins_addTitleToThumbnail' );
If you need any customization or have any questions, feel free to contact us.
Trying to stay on top of it all? Get the best tools, resources and inspiration sent to your inbox every Wednesday.