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:
explode(',', $srcset);
– splits thesrcset
string into an array of images by commas.list($url, $width) = array_map('trim', explode(' ', trim($image)));
– separates each image into a URL and width.intval($width);
– converts the width to an integer so it can be compared.- 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.