I need the same functionality as default WordPress wp_calculate_image_srcset()
method which returns the string for srcset:
image-300x200.jpg 300w, image-600x400.jpg 600w, ...
but it should return an array instead of string, with structure similar to:
$image_sizes = array(
array(
'url' => 'image-300x200.jpg',
'width' => 300,
'height' => 200
),
array(
'url' => 'image-600x400.jpg',
'width' => 600,
'height' => 400
),
array(
'url' => 'image.jpg',
'width' => 1200,
'height' => 800
)
);
I understand that I can just parse the string itself, but I wonder if it’s safe? The plugin that I’m making is public and can be used on any server with other plugins that might modify this string.
Source of wp_calculate_image_srcset
seems complicated and uses a few “_private” methods.
The wp_calculate_image_srcset
is also using max_srcset_image_width
filter (which limits maximum size of image) and I need to avoid it somehow. Is remove_filter -> execute method -> add_filter the only way to skip it?
Edit: I ended up doing this (if it’s a bad idea – please let me know):
class MyClass {
public $image_items;
function __construct() {
add_filter('wp_calculate_image_srcset', array($this, 'filter_my_srcset'), 10, 5);
wp_calculate_image_srcset( ... );
remove_filter('wp_calculate_image_srcset', array($this, 'filter_my_srcset'));
// print_r( $this->image_items );
}
public function filter_my_srcset( $source, ... ) {
$this->image_items = $source;
return $source;
}
}