Добавить настраиваемое поле оформления заказа в зависимости от категории товара в Woocommerce - PullRequest
0 голосов
/ 24 февраля 2019

Мне нужно добавить настраиваемое поле оформления заказа в зависимости от категории продукта.Я нашел этот код, который работает с продуктами, но очень много времени занимает добавление идентификаторов для каждого нового продукта из определенной категории.

function is_in_cart() {
    // Add your special product IDs here
    $ids = array( 12468, 9687, 9693);

    foreach( WC()->cart->get_cart() as $cart_item ){
        $product_id = version_compare( WC_VERSION, '3.0', '<' ) ? $cart_item['data']->id : $cart_item['data']->get_id();
        if( in_array( $cart_item['data']->get_id(), $ids ) )
            return true;
    }
    return false;
}

 /**
 * Add the field to the checkout
 */
add_action( 'woocommerce_before_order_notes', 'custom_checkout_field', 20 );

function custom_checkout_field( $checkout ) {
if( ! is_in_cart() ){
    woocommerce_form_field( 'special_field', array(
        'type'          => 'textarea',
        'class'         => array('form-row-wide'),
        'label'         => pll__('Special text'),
        'required'      => false,
        'label_class'   => array('specialfieldclass'),
        'clear'         => false,
        ), $checkout->get_value( 'special_field' ));
}
}

Как изменить этот код для работы с категориями продуктов?

1 Ответ

0 голосов
/ 24 февраля 2019

Попробуйте выполнить следующие действия для обработки категорий продуктов (также для обработки родительских терминов) :

// Custom conditional function that handle parent product categories too
function has_product_categories( $product_id, $categories ) {
     // Initializing
    $parent_term_ids = $categories_ids = array();
    $taxonomy        = 'product_cat';

    // Convert categories term names and slugs to categories term ids
    foreach ( $categories as $category ){
        if( is_numeric( $category ) ) {
            $categories_ids[] = (int) $category;
        } elseif ( term_exists( sanitize_title( $category ), $taxonomy ) ) {
            $categories_ids[] = get_term_by( 'slug', sanitize_title( $category ), $taxonomy )->term_id;
        }
    }

    // Loop through the current product category terms to get only parent main category term
    foreach( get_the_terms( $product_id, $taxonomy ) as $term ){
        if( $term->parent > 0 ){
            $parent_term_ids[] = $term->parent; // Set the parent product category
            $parent_term_ids[] = $term->term_id; // (and the child)
        } else {
            $parent_term_ids[] = $term->term_id; // It is the Main category term and we set it.
        }
    }
    return array_intersect( $categories_ids, array_unique($parent_term_ids) ) ? true : false;
}

// Custom conditional function that check for product categories
function is_in_cart() {
    // HERE your product categories
    $categories = array( 'clothing' );

    foreach( WC()->cart->get_cart() as $cart_item ){
        if( has_product_categories( $cart_item['product_id'], $categories ) )
            return true;
    }
    return false;
}

 // Add a checkout field before order notes
add_action( 'woocommerce_before_order_notes', 'custom_checkout_field', 20 );
function custom_checkout_field( $checkout ) {
    if( ! is_in_cart() ){
        woocommerce_form_field( 'special_field', array(
            'type'          => 'textarea',
            'class'         => array('form-row-wide'),
            'label'         => pll__('Special text'),
            'required'      => false,
            'label_class'   => array('specialfieldclass'),
            'clear'         => false,
            ), $checkout->get_value( 'special_field' ));
    }
}

Код находится в файле function.php вашей активной дочерней темы (или активной темы).Должно работать.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...