How to get a link to the largest image from srcset in php, WordPress?

In WordPress, the <img> tag with the srcset attribute can contain multiple image URLs with different sizes. To extract the URL of the largest image from srcset in PHP, you need to parse this attribute and select the image with the largest width.

Example code for WordPress:

function get_largest_image_from_srcset($srcset) {
    // Split the srcset string into individual elements
    $images = explode(',', $srcset);
    
    // Initialize variables to store the largest image
    $largest_image = '';
    $max_width = 0;
    
    foreach ($images as $image) {
        // Trim spaces and split into parts: URL and width
        list($url, $width) = array_map('trim', explode(' ', trim($image)));
        
        // Remove "w" from the width and convert it to an integer
        $width = intval($width);
        
        // Check if the width is greater than the current maximum, and update if so
        if ($width > $max_width) {
            $max_width = $width;
            $largest_image = $url;
        }
    }
    
    // Return the URL of the largest image
    return $largest_image;
}

// Example usage in WordPress
$post_thumbnail_id = get_post_thumbnail_id();
$srcset = wp_get_attachment_image_srcset($post_thumbnail_id);
$largest_image = get_largest_image_from_srcset($srcset);

echo $largest_image; // Outputs the URL of the largest image

Explanations:

  1. explode(',', $srcset); – splits the srcset string into an array of images by commas.
  2. list($url, $width) = array_map('trim', explode(' ', trim($image))); – separates each image into a URL and width.
  3. intval($width); – converts the width to an integer so it can be compared.
  4. Checking and updating the maximum width – if the current image is larger in width than the previous one, it updates the value.

This code checks the srcset and returns the URL of the largest image.

How useful is the publication?

Click on a star to rate it!

Average score 5 / 5. Number of grades: 1

No ratings yet. Rate it first.

Similar posts

How to exclude posts with parent post in wp_query, WordPress

To exclude posts that have a parent (i.e., child posts) in a WP_Query request, you can use the post_parent argument. This argument controls whether the post has a parent or not. To exclude child posts, set the condition post_parent => 0, which means that only top-level posts (posts without a parent) will be included in…
Read more