Перенос изображений настраиваемых полей в галерею товаров Woocommerce - PullRequest
1 голос
/ 17 июня 2020

У меня есть несколько настраиваемых полей изображений (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
    }
}

Может ли кто-нибудь помочь или объяснить мне, что не так?

1 Ответ

0 голосов
/ 17 июня 2020

В зависимости от того, где вы запускаете эту функцию, вы должны определить аргумент $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) ); 
    }
}

Код входит в functions. php файл вашей активной дочерней темы (или активной темы). непроверенный, он может работать.

...