function set_featured_image_from_product_gallery() {
$args = array(
'post_type' => 'product', // Change if using a different post type
'posts_per_page' => -1, // Get all products
'meta_query' => array(
array(
'key' => 'product_gallery',
'compare' => 'EXISTS',
),
),
);
$query = new WP_Query($args);
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
$post_id = get_the_ID();
$gallery = get_post_meta($post_id, 'product_gallery', true);
if (!empty($gallery) && is_array($gallery)) {
$image_url = $gallery[0]->Url ?? ''; // Get the first image URL
if (!empty($image_url)) {
$attachment_id = insert_attachment_from_url($image_url, $post_id);
if ($attachment_id) {
set_post_thumbnail($post_id, $attachment_id);
}
}
}
}
wp_reset_postdata();
}
}
add_action('init', 'set_featured_image_from_product_gallery');
function insert_attachment_from_url($image_url, $post_id) {
require_once ABSPATH . 'wp-admin/includes/image.php';
require_once ABSPATH . 'wp-admin/includes/file.php';
require_once ABSPATH . 'wp-admin/includes/media.php';
$image_name = basename($image_url);
$upload_dir = wp_upload_dir();
$image_data = file_get_contents($image_url);
if (!$image_data) {
return false;
}
$file_path = $upload_dir['path'] . '/' . $image_name;
file_put_contents($file_path, $image_data);
$file_type = wp_check_filetype($file_path);
$attachment = array(
'post_mime_type' => $file_type['type'],
'post_title' => sanitize_file_name($image_name),
'post_content' => '',
'post_status' => 'inherit',
);
$attach_id = wp_insert_attachment($attachment, $file_path, $post_id);
$attach_data = wp_generate_attachment_metadata($attach_id, $file_path);
wp_update_attachment_metadata($attach_id, $attach_data);
return $attach_id;
}