将自定义字段图像移动到产品库 Woocommerce

Moving custom field images to product Gallery Woocommerce

我有几个来自旧配置的自定义图像字段 (ACF),并且想将这些图像移动到产品库 (Woocommerce) 中,现在我已将所有数据转换为产品 post 类型。 我试图设置这个函数(在类似 post 中找到),但没有任何反应,也没有返回任何错误:

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
    }
}

有人可以帮我解释一下哪里出了问题吗?

根据您 运行 这个函数的位置,您应该在 ACF get_field() 函数中定义 $product_id 参数。

问题澄清:你是如何运行这个功能的?你在用钩子吗?

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

您的代码也可以简化、优化和压缩如下:

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) ); 
    }
}

代码进入您的活动子主题(或活动主题)的 functions.php 文件。未经测试它可以工作。