WooCommerce:仅允许购物车中同一类别的商品

时间:2017-03-01 04:17:24

标签: php wordpress magento

我想阻止客户在将商品添加到购物车后能够添加其他类别的商品。客户仍应能够添加同一类别的商品。

这是我到目前为止所做的:

function is_product_the_same_cat($valid, $product_id, $quantity) {
    global $woocommerce;
    // start of the loop that fetches the cart items
    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' ); //get the current items
        foreach ($terms as $term) {
            $cat_ids[] = $term->term_id;  //get all the item categories in the cart
        }
        foreach ($target_terms as $term) {
            $target_cat_ids[] = $term->term_id; //get all the categories of the product
        }
    }
    $same_cat = array_intersect($cat_ids, $target_cat_ids); //check if they have the same category
    if(count($same_cat) > 0) return $valid;
    else {
        wc_add_notice( 'This product is in another category!', 'error' );
        return false;
    }
}
add_filter( 'woocommerce_add_to_cart_validation', 'is_product_the_same_cat',10,3);

如果我的购物车中已有商品但是它不允许我从空购物车中添加任何商品并且始终显示错误消息,则此功能正常工作。

谢谢!

2 个答案:

答案 0 :(得分:2)

经过一些调整后,我想我已经弄明白了:

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( 'This product is in another category!', 'error' );
        return false;
    }
}
add_filter( 'woocommerce_add_to_cart_validation', 'is_product_the_same_cat',10,3);

答案 1 :(得分:0)

在您的is_product_the_same_cat方法中,当购物车为空时,您尚未添加任何代码。可能是因为你不能在购物车为空时添加。

在全球$ woocommerce之后添加以下代码;线

if ( woocommerce()->cart->get_cart_contents_count() == 0 ) {
    return true;
}