仅允许在WooCommerce中从父类别相同的产品添加到购物车

时间:2019-06-04 13:52:56

标签: php wordpress woocommerce cart taxonomy-terms

我在商店中使用两个主要的父类别,每个类别又细分为近10个类别。

我有一个脚本,将添加到购物车中的类别数量限制为1个,如何将其更改为仅父类别?所以我可以选择多个相同种类的产品。

function is_product_the_same_cat($valid, $product_id, $quantity) {
    global $woocommerce;
    if($woocommerce->cart->cart_contents_count == 0){
         return true;
    }
    foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
        $_product = $values['data'];
        $terms = get_the_terms( $_product->id, 'product_cat' );
        $target_terms = get_the_terms( $product_id, 'product_cat' );
        foreach ($terms as $term) {
            $cat_ids[] = $term->term_id;  
        }
        foreach ($target_terms as $term) {
            $target_cat_ids[] = $term->term_id; 
        }           
    }
    $same_cat = array_intersect($cat_ids, $target_cat_ids);
    if(count($same_cat) > 0) return $valid;
    else {
        wc_add_notice( 'Solo pueden comprarse productos de una misma categoría.', 'error' );
        return false;
    }
}
add_filter( 'woocommerce_add_to_cart_validation', 'is_product_the_same_cat',10,3);

1 个答案:

答案 0 :(得分:0)

自WooCommerce 3以来,您使用的代码已过时……以下内容适用于父产品类别,仅允许从同一父产品类别添加到购物车中:

add_filter( 'woocommerce_add_to_cart_validation', 'avoid_add_to_cart_from_different_main_categories', 10, 3 );
function avoid_add_to_cart_from_different_main_categories( $passed, $product_id, $quantity ) {
    $cart      = WC()->cart;
    $taxonomy  = 'product_cat';
    $ancestors = [];

    if( $cart->is_empty() )
         return $passed;

    $terms = (array) wp_get_post_terms( $product_id, $taxonomy, array('fields' => 'ids') );

    if( count($terms) > 0 ) {
        // Loop through product category terms  set for the current product
        foreach( $terms as $term) {
            foreach( get_ancestors( $term, $taxonomy ) as $term_id ) {
                $ancestors[(int) $term_id] = (int) $term_id;
            }
        }


        // Loop through cart items
        foreach ( $cart->get_cart() as $item ) {
            $terms = (array) wp_get_post_terms( $item['product_id'], $taxonomy, array('fields' => 'ids') );
            if( count($terms) > 0 ) {
                // Loop through product category terms set for the current cart item
                foreach( $terms as $term) {
                    foreach( get_ancestors( $term, $taxonomy ) as $term_id ) {
                        $ancestors[(int) $term_id] = (int) $term_id;
                    }
                }
            }
        }

        // When there is more than 1 parent product category
        if( count($ancestors) > 1 ) {
            wc_add_notice( __('Only products of the same category can be purchased together.'), 'error' );
            $passed = false; 
        }
    }
    return $passed;
}

代码进入活动子主题(或活动主题)的functions.php文件中。经过测试,可以正常工作。