【问题标题】:Allow only one product to be added to the cart from each category woocommerce [duplicate]仅允许将每个类别 woocommerce 中的一种产品添加到购物车 [重复]
【发布时间】:2023-04-05 09:06:01
【问题描述】:

我试图让客户从每个类别中只添加 1 个产品,例如:牛仔裤、T 恤等。我有这个代码,但我得到的只是一个空白页。此代码检查类别 slug 和产品数量。

add_action( 'woocommerce_check_cart_items', 'check_total' );
    function check_total() {
        // Only run in the Cart or Checkout pages
        if( is_cart() || is_checkout() ) {

            global $woocommerce, $product;

            $total_quantity = 0;
            $display_notice = 1;
            $i = 0;
            //loop through all cart products
            foreach ( $woocommerce->cart->cart_contents as $product ) {

                // See if any product is from the cuvees category or not
                if ( has_term( 'category-1', 'product_cat', $product['product_id'] )) {
                    $total_quantity += $product['quantity'];
                }

            }
            // Set up the acceptable totals and loop through them so we don't have an ugly if statement below.
            $acceptable_totals = array(1, 2, 3, 6, 12, 18, 24, 30, 36, 42, 48, 54, 60, 72, 96, 120);

            foreach($acceptable_totals as $total_check) {
                if ( $total_check == $total_quantity ) { $display_notice = 0; } 
            }

            foreach ( $woocommerce->cart->cart_contents as $product ) {
                if ( has_term( 'category-1', 'product_cat', $product['product_id'] ) ) {
                    if( $display_notice == 1 && $i == 0 ) {
                        // Display our error message
                        wc_add_notice( sprintf( 'This product can only be sold in following quantities 1 | 2 | 3 | 6 | 12 | 18 | 24 | 30 | 36 | 42 | 48 | 54 | 60  | 72 | 96 | 120.</p>', $total_quantity),
                        'error' );
                    }
                    $i++;
                }
            }
        }

【问题讨论】:

  • 在这个相关答案中,您只需将 if( ! has_term( $product_cats, 'product_cat', $cart_item['product_id'] )) { 替换为 if( has_term( $product_cats, 'product_cat', $cart_item['product_id'] )) { ......它就会按照您的预期进行。
  • 但这已经完成了
  • 我在最后做了一个更新,只是为了你的情况……
  • 您在此处发布的解决方案之一stackoverflow.com/questions/39644645/… 似乎足够接近我的需求,我如何向变量添加超过 1 个类别。 $category = '兄弟';
  • @LoicTheAztec stackoverflow.com/questions/42400501/… 为我工作 if( has_term... 如我所愿。

标签: php wordpress woocommerce product-quantity


【解决方案1】:

您应该使用“woocommerce_add_to_cart_validation”挂钩来验证您添加到购物车的过程。

apply_filters( 'woocommerce_add_to_cart_validation',  $true,  $product_id,  $quantity ); 

http://hookr.io/filters/woocommerce_add_to_cart_validation/

【讨论】:

    猜你喜欢
    • 2017-09-27
    • 1970-01-01
    • 1970-01-01
    • 2018-08-07
    • 1970-01-01
    • 2017-03-26
    • 1970-01-01
    • 2018-07-23
    • 2019-03-02
    相关资源
    最近更新 更多