The max_srcset_image_width WordPress PHP filter allows you to modify the maximum image width to be included in a ‘srcset’ attribute.
Usage
add_filter('max_srcset_image_width', 'your_custom_function', 10, 2); function your_custom_function($max_width, $size_array) { // your custom code here return $max_width; }
Parameters
- $max_width (int): The maximum image width to be included in the ‘srcset’. Default is ‘2048’.
- $size_array (int[]): An array of requested width and height values.
- int: The width in pixels.
- int: The height in pixels.
More information
See WordPress Developer Resources: max_srcset_image_width
Examples
Limit the maximum image width in the srcset to 1200 pixels
This code snippet limits the maximum image width in the ‘srcset’ attribute to 1200 pixels.
add_filter('max_srcset_image_width', 'limit_srcset_max_width', 10, 2); function limit_srcset_max_width($max_width, $size_array) { $max_width = 1200; return $max_width; }
Set the maximum image width in the srcset based on the screen size
This code snippet sets the maximum image width in the ‘srcset’ attribute based on the screen size (small, medium, or large).
add_filter('max_srcset_image_width', 'set_srcset_max_width_based_on_screen_size', 10, 2); function set_srcset_max_width_based_on_screen_size($max_width, $size_array) { if ($size_array[0] <= 600) { $max_width = 800; } elseif ($size_array[0] <= 1024) { $max_width = 1200; } else { $max_width = 2048; } return $max_width; }
Set the maximum image width in the srcset to the original image width
This code snippet sets the maximum image width in the ‘srcset’ attribute to the original image width.
add_filter('max_srcset_image_width', 'set_srcset_max_width_to_original', 10, 2); function set_srcset_max_width_to_original($max_width, $size_array) { $max_width = $size_array[0]; return $max_width; }
Increase the maximum image width in the srcset by 50%
This code snippet increases the maximum image width in the ‘srcset’ attribute by 50%.
add_filter('max_srcset_image_width', 'increase_srcset_max_width_by_50', 10, 2); function increase_srcset_max_width_by_50($max_width, $size_array) { $max_width = $max_width * 1.5; return $max_width; }
Decrease the maximum image width in the srcset by 25%
This code snippet decreases the maximum image width in the ‘srcset’ attribute by 25%.
add_filter('max_srcset_image_width', 'decrease_srcset_max_width_by_25', 10, 2); function decrease_srcset_max_width_by_25($max_width, $size_array) { $max_width = $max_width * 0.75; return $max_width; }