X

How to call wp_get_attachment_image() without srcset

Sometimes it’s nice to have all the goodies wrapped up in a nice little function, such as wp_get_attachment_image(). This is a great function that generates the entire html for an image tag, including srcset and sizes.

However, wouldn’t it be great if sometimes we could get all the goodness from this wonderful function, but just for the one image size we’ve requested?

Say hello to a simple wrapper

At this stage you may be thinking that you can achieve this with a simple wp_calculate_image_srcset_meta filter, that will return null when the srcset is called?

And you’d be on the right path! But it’s not quite the answer because we don’t want to disable srcset on a global scale.

What we need is the option to temporarily disable srcset on-the-fly. And for this we can write a simple wrapper function;

wp_get_attachment_image_no_srcset()

In this function we will only disable srcset whilst we’re generating the HTML for an image that we only want a single source URL for, like so:

/**
 * Get an HTML img element representing an image attachment
 *
 * returns wp_get_attachment_image without a srcset
 * @param int          $attachment_id Image attachment ID.
 * @param string|array $size          (Optional)
 * @param bool         $icon          (Optional)
 * @param string|array $attr          (Optional)
 * @return string      HTML img element or empty string.
 */function wp_get_attachment_image_no_srcset($attachment_id, $size = 'thumbnail', $icon = false, $attr = '') {
    // add a filter to return null for srcset
    add_filter( 'wp_calculate_image_srcset_meta', '__return_null' );
    // get the srcset-less img html
    $html = wp_get_attachment_image($attachment_id, $size, $icon, $attr);
    // remove the above filter
    remove_filter( 'wp_calculate_image_srcset_meta', '__return_null' );
    return $html;
}

And that’s it, wp_get_attachment_image_no_srcset() – a simple wrapper function. Call this, function instead of wp_get_attachment_image(), whenever you want all its goodness minus srcset.

Plonk this function in your theme, or better still, in an extended functionality plugin, and you’re good to go with/without srcset.

Need help?

Feel free to use this at will and please let us know if you require any help with WordPress (or any other) development. We’re seasoned developers with many years experience building custom WordPress themes and plugins. We are dedicated and focused on performance and search engine optimisation.

Related Post

This website uses cookies.