For products, I have several custom attributes set up and among them is images
which can have multiple images separated by |
. You can have a look Here. The products were inserted through woocommerce api. But the issues is the featured image which is responsible for showing the image in the frontend, isn’t filled up. So I need to take the first image from the images
attribute and set it as featured image. As they are already existing product so I tried to implement through the code below and added it in my functions.php
. But it didn’t work
function update_existing_products_featured_image() {
$attribute_name = 'images';
// Get all published simple products
$args = array(
'post_type' => 'product',
'posts_per_page' => -1,
'fields' => 'ids',
'post_status' => 'publish',
);
$product_ids = get_posts($args);
foreach ($product_ids as $product_id) {
// Get the custom attribute value for the product
$attribute_value = get_post_meta($product_id, '_' . $attribute_name, true);
// Check if the attribute value contains '|' to separate images
if ($attribute_value && strpos($attribute_value, '|') !== false) {
// Explode the attribute value to get an array of image URLs
$image_urls = explode('|', $attribute_value);
// Get the first image URL from the array
$first_image_url = trim($image_urls[0]);
// Check if the first image URL is valid
if (filter_var($first_image_url, FILTER_VALIDATE_URL)) {
// Download the image and set it as the featured image
$image_id = media_sideload_image($first_image_url, $product_id, '', 'id');
set_post_thumbnail($product_id, $image_id);
}
}
}
}
update_existing_products_featured_image();
Any suggestions on this?
2
Answers
After much digging I solved it using
add_filter
hook in woocommerceHere I set the img src instead of setting it as a featured image...works fine for my use case.
i work an similar solution…
if I find my solution, I will share it here with you.