This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.
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 a filter hook, and it filters the HTML of the post thumbnail. It is 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 Examples
Example 1: Basic Usage
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... }
Example 2: Adding a Hook Callback
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 );
Example 3: Removing a Hook Callback
To remove a hook callback, use the example below:
// remove the filter remove_filter( 'post_thumbnail_html', 'weplugins_filter_post_thumbnail_html', 10, 5 );
Example 4: Adding Title Attribute to Thumbnail
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' );
Contact Us
If you need any customization or have any questions, feel free to contact us.
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.