首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将自定义字段图像移动到产品库Woocommerce

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

Stack Overflow用户
提问于 2020-06-17 17:10:17
回答 1查看 471关注 0票数 1

我有几个来自旧配置的自定义映像字段(ACF),并且希望将这些图像移到Product (Woocommerce)中,现在我已经将所有数据转换为Product类型。我试图设置这个函数(在类似的帖子中找到),但是什么也没有发生,也没有返回错误:

代码语言:javascript
复制
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
    }
}

有人能帮我解释一下怎么回事吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-06-17 20:39:11

根据运行此函数的位置,应该在ACF get_field()函数中定义get_field()参数。

问题来澄清:如何运行这个函数?你在用钩子吗?

Update:将函数挂在woocommerce_process_product_meta中,因此当产品被创建或更新时,它将触发代码。

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

代码语言:javascript
复制
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文件中。未经测试就能成功。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62434585

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档