I want to disable the srcset only when calling a specific thumbnail
size (for example only when calling full image size).
Here are two ideas (if I understand you correctly):
Approach #1
Let’s check the size from the post_thumbnail_size
filter. If it matches a corresponding size (e.g. full
) then we make sure the $image_meta
is empty, with the wp_calculate_image_srcset_meta
filter. That way we can bail out early from the wp_calculate_image_srcset()
function (earlier than using the max_srcset_image_width
or wp_calculate_image_srcset
filters to disable it):
/**
* Remove the srcset attribute from post thumbnails
* that are called with the 'full' size string: the_post_thumbnail( 'full' )
*
* @link http://wordpress.stackexchange.com/a/214071/26350
*/
add_filter( 'post_thumbnail_size', function( $size )
{
if( is_string( $size ) && 'full' === $size )
add_filter(
'wp_calculate_image_srcset_meta',
'__return_null_and_remove_current_filter'
);
return $size;
} );
// Would be handy, in this example, to have this as a core function ;-)
function __return_null_and_remove_current_filter ( $var )
{
remove_filter( current_filter(), __FUNCTION__ );
return null;
}
If we have:
the_post_thumbnail( 'full' );
then the generated <img>
tag will not contain the srcset
attribute.
For the case:
the_post_thumbnail();
we could match the 'post-thumbnail'
size string.
Approach #2
We could also add/remove the filter manually with:
// Add a filter to remove srcset attribute from generated <img> tag
add_filter( 'wp_calculate_image_srcset_meta', '__return_null' );
// Display post thumbnail
the_post_thumbnail();
// Remove that filter again
remove_filter( 'wp_calculate_image_srcset_meta', '__return_null' );