Something like this should work
Your function for the responsive images
function custom_responsive_image($image_id, $breakpoints, $custom_class = '') {
// Initialize srcset and sizes strings
$srcset = [];
$sizes = [];
// Loop through the breakpoints to build the srcset and sizes arrays
foreach ($breakpoints as $breakpoint => $size) {
$image_src = wp_get_attachment_image_src($image_id, $size['size']);
if ($image_src) {
$srcset[] = $image_src[0] . ' ' . $image_src[1] . 'w';
$sizes[] = "(min-width: {$breakpoint}px) {$image_src[1]}px";
}
}
// Get the alt text for the image
$alt_text = get_post_meta($image_id, '_wp_attachment_image_alt', true);
$alt_text = !empty($alt_text) ? $alt_text : 'Fallback alt text';
// Combine srcset and sizes arrays into strings
$srcset_string = implode(', ', $srcset);
$sizes_string = implode(', ', $sizes);
// Get the smallest image as the default src
$default_image = wp_get_attachment_image_src($image_id, $breakpoints[min(array_keys($breakpoints))]['size']);
// Return the image HTML
return '<img src="' . esc_url($default_image[0]) . '" class="' . esc_attr($custom_class) . '" srcset="' . esc_attr($srcset_string) . '" sizes="' . esc_attr($sizes_string) . '" alt="' . esc_attr($alt_text) . '">';
}
Register your custom image sizes
function my_custom_image_sizes() {
// Add custom image sizes
add_image_size('256x144', 256, 144, true); // For min-width: 0px
add_image_size('750x422', 750, 422, true); // For min-width: 576px
add_image_size('1190x670', 1190, 670, true); // For min-width: 768px
add_image_size('1500x844', 1500, 844, true); // For min-width: 992px
add_image_size('1800x1013', 1800, 1013, true); // For min-width: 1200px
add_image_size('2048x1152', 2048, 1152, true); // For min-width: 1400px
}
add_action('after_setup_theme', 'my_custom_image_sizes');
to use it in your theme
<?php
$image_id = get_post_thumbnail_id();
echo custom_responsive_image($image_id, array(
0 => ['size' => '256x144'],
576 => ['size' => '750x422'],
768 => ['size' => '1190x670'],
992 => ['size' => '1500x844'],
1200 => ['size' => '1800x1013'],
1400 => ['size' => '2048x1152']
), 'image--responsive);
?>