Skip to content
Advertisement

Moving custom field images to product Gallery Woocommerce

I’ve several custom image fields (ACF) from an old configuration, and would like to move those images in the Product Gallery (Woocommerce), now I’ve converted all the datas into a Product post type. I tried to set this function (found in a similar post), but nothing happens, and no errors returned neither :

function upload_all_images_to_product($product_id, $image_id_array) {
    //define the array with custom fields images
    $image_1 = get_field('images'); // should returns image IDs
    $image_2 = get_field('images-2');
    $image_3 = get_field('images-3');
    $image_4 = get_field('images-4');
    $image_5 = get_field('images-5');
    $image_6 = get_field('images-6');

    $image_id_array = array($image_1, $image_2, $image_3, $image_4, $image_5, $image_6);

    //take the first image in the array and set that as the featured image
    set_post_thumbnail($product_id, $image_id_array[0]);

    //if there is more than 1 image - add the rest to product gallery
    if(sizeof($image_id_array) > 1) { 
        array_shift($image_id_array); //removes first item of the array (because it's been set as the featured image already)
        update_post_meta($product_id, '_product_image_gallery', implode(',',$image_id_array)); //set the images id's left over after the array shift as the gallery images
    }
}

Could someone help or explain me what’s wrong ?

Advertisement

Answer

Depending on where you run this function, you should define the $product_id argument in ACF get_field() function.

Questions to clarify: How do you run this function? are you using a hook?

Update: Hooked the function in woocommerce_process_product_meta, so when a product is created or updated, it will trigger the code.

Also your code can be simplified, optimized and compacted as follow:

add_action( 'woocommerce_process_product_meta', 'save_my_custom_settings' );
function upload_all_images_to_product( $product_id, $image_ids = array(); ) {
    // Loop from 1 to 6
    for ( $i = 1; $i <= 6; $i++ ) {
        $field_key = 'images'.( $i == 1 ? '' : '-'.$i );

        // Check that the custom field exists
        if( $field_value = get_field( $field_key, $product_id ) )
            $image_ids[] = $field_value; // Set each ACF field value in the array
    }

    if( ! empty($image_ids) ) { 
        // Take the first image (removing it from the array) and set it as the featured image
        set_post_thumbnail( $product_id, array_shift($image_ids) );
    }

    if( ! empty($image_ids) ) {     
        // Set the remaining array images ids as a coma separated string for gallery images
        update_post_meta( $product_id, '_product_image_gallery', implode(',', $image_ids) ); 
    }
}

Code goes in functions.php file of your active child theme (or active theme). untested it could work.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement