【问题标题】:Restrict cart to be able to only contain 1 "Brand"限制购物车只能包含 1 个“品牌”
【发布时间】:2020-11-13 08:21:50
【问题描述】:

我正在使用 WooCommerce 和 WooCommerce Brands 创建分类“product_brand”。

我需要限制购物车,以便客户只能购买单个“品牌”的产品,如果他们尝试将其他品牌的产品输入购物车,它应该会显示一条消息,说明如下:

多个品牌的产品不能包含在同一个购物车中。 (按钮 - “清除购物车并添加”)

如果还可以添加一个按钮,允许客户“清除购物车并添加”他们尝试购买的产品,那就太好了。

【问题讨论】:

  • 您应该提供您真正自己的代码尝试。请注意,StackOverFlow 不是免费的编码服务。

标签: php wordpress woocommerce


【解决方案1】:

要实现此复制/粘贴下面的自定义函数到您的子主题functions.php 或使用名为Code Snippets 的插件。

add_filter( 'woocommerce_add_to_cart_validation', 'add_to_cart_validation_callback', 10, 3 );
function add_to_cart_validation_callback( $passed, $product_id, $quantity) {
    // HERE set your alert text message
    $message = __( 'Unable to add to cart: You may only checkout with one club at a time.', 'woocommerce' );

    if( ! WC()->cart->is_empty() ) {
        // Get the product brand terms for the current product
        $terms_slugs = wp_get_post_terms( $product_id, 'product_brand', array('fields' => 'slugs'));

        // Loop through cart items
        foreach (WC()->cart->get_cart() as $cart_item ){
            if( ! has_term( $terms_slugs, 'product_brand', $cart_item['product_id'] )) {
                $passed = false;
                wc_add_notice( $message, 'error' );
                break;
            }
        }
    }
    return $passed;
}

【讨论】:

    猜你喜欢
    • 2014-05-03
    • 1970-01-01
    • 2018-02-10
    • 2020-01-14
    • 2023-01-31
    • 2013-07-10
    • 1970-01-01
    • 2015-10-24
    • 1970-01-01
    相关资源
    最近更新 更多