post_thumbnail_html
To alter the html output, you need to hook the filter post_thumbnail_html
From Codex:
apply_filters( 'post_thumbnail_html', string $html, int $post_id,
string $post_thumbnail_id, string|array $size, string $attr )
Filters the post thumbnail HTML.
This filter is called by get_the_post_thumbnail
on line 177 of post_thumbnail_template.php after $html
has been set with:
$html = wp_get_attachment_image( $post_thumbnail_id, $size, false, $attr );
Filter in context:
/**
* Filters the post thumbnail HTML.
* @param string $html The post thumbnail HTML.
* @param int $post_id The post ID.
* @param string $post_thumbnail_id The post thumbnail ID.
* @param string|array $size The post thumbnail size. Image size or array of width and height values (in that order). Default 'post-thumbnail'.
* @param string $attr Query string of attributes.
*/
return
apply_filters( 'post_thumbnail_html', $html, $post->ID, $post_thumbnail_id, $size, $attr );
Adding data-featherlight="mylightbox"
example:
So adding your data-featherlight="mylightbox"
would perhaps be something like:
add_filter('post_thumbnail_html', 'my_thumbnail_filter_method', 10, 5 );
function my_thumbnail_filter_method($html, $post->ID, $post_thumbnail_id, $size, $attr) {
$id = get_post_thumbnail_id();
$src = wp_get_attachment_image_src($id, $size);
$alt = get_the_title($id); /
$class = $attr['class'];
$html = '<img src="' . $src[0] . '" alt="' . $alt . '" class="' . $class . '" data-featherlight="mylightbox" />';
}
Two other action hooks are present on either side of $html
being set within get_the_pos_thumbnail
.
begin_fetch_post_thumbnail_html
end_fetch_post_thumbnail_html
but both are only passing $post->ID, $post_thumbnail_id, $size
.
So, it looks like filtering post_thumbnail_html
is the best way to access the <img>
html string.
A note on has_post_thumbnail()
, since it seems to come up often:
this method will return true if any images are attached to post, not specifically for the post thumbnail (aka featured image).