In this short post, we will see how to disable the automatic addition of the srcset
attribute to the html
of images on WordPress sites. If you take a look at the source code of a page on your website that contains images, you will discover that the tags contain one or more
srcset
attributes.
In essence, the srcset
attribute is added to each image to allow the browser to determine which image size to apply based on the specific resolution and screen size of a device.
srcset
is a very useful feature for displaying responsive images and looks something like this:
<img src="/demo-200px.png" srcset="/demo-200px.png 1x, /demo-400px.png 2x">
However, in certain cases, you might want to disable the automatic addition of this attribute. Here’s how to do it…
Disabling the Automatically Added srcset Attribute on WordPress Sites
To disable this option site-wide, add the following code to the functions.php
file of your child theme:
function sv_disable_srcset( $sources ) {
return false;
}
add_filter( 'wp_calculate_image_srcset', 'sv_disable_srcset' );
If you want to remove the srcset
attribute from images in a specific location within the template, for example, when using the the_post_thumbnail()
function, you can do it as follows:
remove_filter( 'wp_calculate_image_srcset_meta', '__return_null' ); // Remove that filter
the_post_thumbnail(); // Display the post thumbnail
add_filter( 'wp_calculate_image_srcset_meta', '__return_null' ); // Add srcset filter back
Up to this point, I’m confident that as WordPress developers, you will find a use for the approach I presented sooner or later… Good luck!