wordpress 在WooComerce中每个订单只允许一个类别

68bkxrlz  于 2022-12-22  发布在  WordPress
关注(0)|答案(1)|浏览(124)

我试图限制我的WooCommerce商店的客户一次只能从1个类别订购。
我正在尝试的代码只是出于某种原因限制了一切。

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

我不想限制它每个类别1个产品,我试图限制他们,使他们只能从1个类别的产品每个订单。
例如,一旦他们从“糖果”类别中添加了一个产品到购物篮中,他们就不能从“糖果”以外的任何其他类别中添加产品。

vddsk6oq

vddsk6oq1#

假设每个产品仅包含1个类别

function filter_woocommerce_add_to_cart_validation( $passed, $product_id, $quantity, $variation_id = null, $variations = null ) {
    // If passed
    if ( $passed ) {
        
        // If cart is NOT empty when a product is added     
        if ( !WC()->cart->is_empty() ) {
            
            // Set vars
            $current_product_category_ids = array();
            $in_cart_product_category_ids = array();
            
            // Get current product categories via product_id
            $current_product_category_ids = wc_get_product_term_ids( $product_id, 'product_cat' );

            // Loop through cart items checking for product categories
            foreach ( WC()->cart->get_cart() as $cart_item ) {
                // Get product categories from product in cart via cart item product id
                $in_cart_product_category_ids = array_merge( $in_cart_product_category_ids, wc_get_product_term_ids( $cart_item['product_id'], 'product_cat' ) );
            }
            
            // Removes duplicate values
            $in_cart_product_category_ids = array_unique( $in_cart_product_category_ids, SORT_NUMERIC );
            
            // Compare
            $compare = array_diff( $current_product_category_ids, $in_cart_product_category_ids );
            
            // Result is NOT empty
            if ( !empty ( $compare ) ) {
                wc_add_notice( 'This product is in another category!', 'error' );
                $passed = false;
            }
        }
    }

    return $passed;
}
add_filter( 'woocommerce_add_to_cart_validation', 'filter_woocommerce_add_to_cart_validation', 10, 5 );

相关问题