Last active
August 9, 2024 18:23
-
-
Save daguitosama/c5adee65012e349741a525420c680f82 to your computer and use it in GitHub Desktop.
Add srcSet data to Images on WooCommerce REST API response
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
Plugin Name: Add SRCSET data to images | |
Description: Adds srcset information to WooCommerce product images in the REST API. | |
Version: 1.0 | |
Author: Dago | |
*/ | |
add_filter('woocommerce_rest_prepare_product_object', 'add_srcset_to_product_images', 10, 3); | |
function add_srcset_to_product_images($response, $product, $request) { | |
$images = $response->get_data()['images']; | |
foreach ($images as &$image) { | |
// Get the full URL for the image | |
$image_url = wp_get_attachment_url($image['id']); | |
// Generate the srcset attribute | |
$srcset = wp_get_attachment_image_srcset($image['id']); | |
// Add the full URL and srcset to the image array | |
$image['src'] = $image_url; // Ensure the 'src' is the full URL | |
$image['srcset'] = $srcset; // Add the srcset attribute | |
} | |
// Update the images in the response | |
$response->data['images'] = $images; | |
return $response; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment