Image Gallery

How to Remove Srcset from wp_get_attachment_image() in WordPress

Learn how to remove srcset from wp_get_attachment_image() for WordPress, so you can display consistently sized attachment images every time.

wp_get-attachment_image() is WordPress’s built-in function to create an <img /> tag, so you can display a media file on your website. By default, it includes a srcset attribute.

A srcset is a set of image sources (i.e. “src set”) used for rendering responsively-sized images. Most of the time that’s a desirable thing, but sometimes — like if you need to create a consistently sized grid of your company’s team members or employees and you don’t have consistently sized photos of everyone — it’s better to leave out the srcset attribute to afford yourself the opportunity to use a larger-than-necessary-image and apply a crop.

Solution

Essentially, you can add a filter and return null for wp_calculate_image_srcset_meta. However, you also need to remove the filter on-the-fly or else it will get applied site-wide and that’s no good. This needs to be available on an as-needed basis.

Here’s the code for the function with the filter.

/**
 * Get a WordPress attachment image without a srcset attribute.
 *
 * @param int $attachment_id Image attachment ID.
 * @param string|array $size (optional)
 * @param bool $icon (optional)
 * @param string|array $attr (optional)
 *
 * @return string img element or an empty string.
 */
function wp_get_attachment_image_without_srcset($attachment_id, $size = 'full', $icon = false, $attr = '') {
    // Add a filter to return null for srcset.
    add_filter( 'wp_calculate_image_srcset_meta', '__return_null' );
    // Get the attachment image sans-srcset attribute.
    $result = wp_get_attachment_image($attachment_id, $size, $icon, $attr);
    // Remove the null srcset filter, to avoid global application.
    remove_filter( 'wp_calculate_image_srcset_meta', '__return_null' );
    return $result;
}

Add that to your WordPress theme’s function.php, so you can use it in your templates.

Usage

Using the new function in your theme templates is essentially the same as using the original wp_get_attachment_image() function except now you have a new function-name to call when you want to get an image without the srcset attribute.

Example:

echo wp_get_attachment_image_without_srcset($attachment_id, array(700, 700), false, array( 'class' => 'your-custom-image-class' ));

And, there you have it. Use WordPress and do cool stuff on your website.