Woocommerce根据产品类别单独销售

时间:2018-01-18 07:20:24

标签: php wordpress woocommerce cart categories

我有一个woocommerce网站,我使用booster插件为每个产品单独销售,但现在我想为每个类别单独销售,如果有人将产品添加到某个类别的购物车,则无法添加该类别的其他产品购物车

2 个答案:

答案 0 :(得分:1)

在下面的代码中有2个函数:

  • 第一个是购物车商品中的条件函数检查类别
  • 当购物车商品中已存在产品类别并且会显示自定义消息时,第二个将避免添加到购物车。

代码:

// Conditional function: Checking product categories in cart items
function check_cats_in_cart( $product_id ) {
    $taxonomy = 'product_cat';
    $has_term = true;

    foreach( WC()->cart->get_cart() as $item ){
        foreach( wp_get_post_terms( $item['product_id'], $taxonomy ) as $term ){
            // Allowing add to cart the same product
            if( has_term( $term->slug, $taxonomy, $product_id ) ){
                $has_term = false;
                break; // stops the 2nd loop
            }
        }
        // Allowing the same product to be added (not activated. you can uncomment lines below)
        # if ( $item['product_id'] == $product_id  )
        #   $has_term = true;

        if( $has_term )
            break; // stops the 1st loop
    }
    return $has_term;
}

// Avoid add to cart when a product category already exist in cart items, displaying a custom error message
add_filter( 'woocommerce_add_to_cart_validation', 'sold_individually_by_cats_valid', 10, 3 );
function sold_individually_by_cats_valid( $passed, $product_id, $quantity) {

    $passed = check_cats_in_cart( $product_id );

    if( ! $passed ){
        // Displaying a custom message
        $message = __("This product category is already in cart. Try another product", "woocommerce");
        wc_add_notice( $message, 'error' );
    }
    return $passed;
}

代码进入活动子主题(或活动主题)的function.php文件。

经过测试和工作。

  

如果您想允许再次向购物车添加相同的产品(仅增加现有产品的数量),您将在功能中取消注释此代码:

       if ( $item['product_id'] == $product_id  )
            $has_term = true;

答案 1 :(得分:0)

你可以试试这个

dict1={}
dict1['a']= 'one %s two'
dict2=dict1
print(dict1)
dict2['a']=dict1['a'] % 'less than' # changing one of dict2 values, 
print(dict1)                        # but also changes dict 1 value 
                                    # with same key

我是从here

找到的