【问题标题】:WooCommerce: Only allow products from the same category in cartWooCommerce:仅允许购物车中同一类别的产品
【发布时间】:2017-03-01 04:17:24
【问题描述】:

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

这是我目前所拥有的:

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);

如果我的购物车中已经有一件商品,但它不允许我从空购物车中添加任何东西并始终显示错误消息,则此方法有效。

谢谢!

【问题讨论】:

    标签: php wordpress magento


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

    【讨论】:

    • 这正是我自己的项目所需要的。
    【解决方案2】:

    在您的is_product_the_same_cat 方法中,您没有添加任何代码以在购物车为空时执行。可能是因为购物车为空时无法添加。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-02
      • 2021-01-17
      • 1970-01-01
      • 2017-09-27
      • 2019-10-20
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多