Разрешить только один продукт (такой же, но только для родительских категорий продуктов) в корзину одновременно в Woocommerce - PullRequest
0 голосов
/ 07 ноября 2019

add_filter ('woocommerce_add_to_cart_validation', 'only_one_product_category_allowed', 20, 3);function only_one_product_category_allowed ($ пройдено, $ product_id, $ количество) {$ parent_term_ids = $ item_parent_term_ids = array ();// Инициализация

// Loop through the current product category terms to get only parent main category term
foreach( get_the_terms( $product_id, 'product_cat' ) as $term ){
    if( $term->parent > 0 ){
        $parent_term_ids[] = $term->parent; // Set the parent product category
    }
}

// Loop through cart items
foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item ){
    // Loop through the cart item product category terms to get only parent main category term
    foreach( get_the_terms( $cart_item['product_id'], 'product_cat' ) as $term ){
        if( $term->parent > 0 ){
            $item_parent_term_ids[] = $term->parent; // Set the parent product category
        }
    }

    // Check if parent product categories don't match
    if( ! array_intersect( $parent_term_ids, $item_parent_term_ids ) ){

        // Displaying a custom notice
        wc_add_notice( __('Only items from one product category are allowed in cart'), 'error' );

        // Avoid add to cart
        return false; // exit
    }
}
return $passed;

}

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