根据子产品类别限制 WooCommerce 购物车

时间:2021-04-07 19:18:36

标签: php wordpress woocommerce

我希望使用 WooCommerce 的添加到购物车验证来限制特定类别的操作。

我有两个父类别:Cat A 和 Cat B。

对于A类,应该是不受限制的。所以,它可以随时加入购物车。

对于 Cat B,我有不同的子类别。我希望对其进行限制,以便在任何时候购物车中都只能存在 Cat B 中的一个子类别。如果有人尝试将第二个 Cat B 儿童类别产品添加到购物车,而购物车中已有冲突的儿童猫,我希望显示错误消息。

子类别将不断变化,因此不能通过子猫 ID 进行查询——它必须通过父类别来完成。也可以选择将所有 Cat B 子类别设为父类别,但我仍然需要将 Cat A 从限制中排除。

基于 Allow only one product per product category in cart 的回答代码,这是我目前所拥有的,我试图让购物车循环仅在添加的产品不是来自 Cat A 的情况下运行:

def jump():
   player.y += 10 
    ...

commands = {"jump":jump,"Run":run,"Swim":swim}
for cmd in command_file.split("\n"):
    commands.get(cmd.strip())()

这满足了我对 Cat B 产品的要求,但也限制了我不想要的 Cat A。

虽然有类似的问题有可靠的答案,但我还没有找到可以解决我的问题的问题。我似乎无法让它忽略 Cat A 使其不受限制,或者正确读取子类别。

1 个答案:

答案 0 :(得分:0)

如果你的代码按照类别B的逻辑,你可以添加这个控件总是允许将属于类别A的产品加入购物车:< /p>

// if the product belongs to category A allows the addition of the product to the cart
if ( has_term( 'cat-a-slug', 'product_cat', $product_id ) ) {
    return $passed;
}

所以完整的功能将是:

add_filter( 'woocommerce_add_to_cart_validation', 'custom_checking_product_added_to_cart', 10, 3 );
function custom_checking_product_added_to_cart( $passed, $product_id, $quantity) {

    // if the product belongs to category A allows the addition of the product to the cart
    if ( has_term( 'cat-a-slug', 'product_cat', $product_id ) ) {
        return $passed;
    }

    // Getting the product categories slugs in an array for the current product
    $product_cats_object = get_the_terms( $product_id, 'product_cat' );
    foreach ( $product_cats_object as $obj_prod_cat ) {
        $product_cats[] = $obj_prod_cat->slug;
    }

    // if the product belongs to category B
    if ( in_array( 'cat-b-slug', $product_cats ) ) {
        // Iterating through each cart item
        foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {

            // When the product category of the current product does not match with a cart item
            if ( ! has_term( $product_cats, 'product_cat', $cart_item['product_id'] ) ) {
                // Don't add 
                $passed = false;
                
                // Displaying a message
                wc_add_notice( 'Only one product from a category is allowed in cart', 'error' );

                // We stop the loop
                break;
            }
        }
    }

    return $passed;
}

我还没有测试过代码,但它应该可以工作。将它添加到您的活动主题的functions.php。