移动自定义字段图片到产品图库Woocommerce。

问题描述 投票:0回答:1

我有几个自定义的图像字段(ACF)从一个旧的配置,并希望将这些图像在产品库(Woocommerce),现在我已经转换所有的数据到一个产品的职位类型.我试图设置这个功能(发现在一个类似的帖子),但什么都没有发生,也没有错误返回。

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

谁能帮助我或解释一下是什么问题?

wordpress function woocommerce advanced-custom-fields
1个回答
0
投票

根据你运行这个函数的地方,你应该定义的是 $product_id 在ACF中的参数 get_field() 职能。

要说明的问题。 你是如何运行这个函数的 你是在用钩子吗?

更新: 钩住功能 woocommerce_process_product_meta,所以当有产品创建或更新时,会触发代码。

你的代码也可以简化,优化和压缩如下。

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

代码放在你的活动子主题(或活动主题)的function.php文件中,未经测试可以使用。

© www.soinside.com 2019 - 2024. All rights reserved.