Exciting News! Flipper Code is now WePlugins! Same commitment to excellence, brand new identity.

How to use post_thumbnail_html filter in WordPress

Sandeep Kumar Mishra
Sandeep Kumar Mishra
July 7, 2022
5 minutes read

post_thumbnail_html filter

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 )

Description

This is filter hook , its filter the HTML of post thumbnail. Its used for rewriting the HTML output for post thumbnails.

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.

Live Example

To run the hook, 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 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', 'filter_post_thumbnail_html', 10, 5 );  

To remove a hook callback, use the example below.

// remove the filter 
remove_filter( 'post_thumbnail_html', 'filter_post_thumbnail_html', 10, 5 ); 

 

function wpdocs_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', 'wpdocs_addTitleToThumbnail' );
Sandeep Kumar Mishra

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.

Explore the latest in WordPress

Trying to stay on top of it all? Get the best tools, resources and inspiration sent to your inbox every Wednesday.