如何防止从两类woocommerce添加产品?

时间:2016-02-09 12:17:48

标签: wordpress wordpress-plugin woocommerce

我正在寻找限制用户添加来自不同产品类别的产品的代码。即如果用户从A类别添加产品,并且当他尝试添加B类别的产品时,会出现一条消息,说明"您可以一次从一个类别下订单并重定向到链接。

1 个答案:

答案 0 :(得分:-1)

根据您的要求,这不是完美的答案,需要进行一些修改,但它肯定会为您提供解决方案的线索:

add_filter ( 'woocommerce_before_cart', 'restrict_cart_for_a_single_category' );
function restrict_cart_for_a_single_category() {
        global $woocommerce;
        $cart_contents    =  $woocommerce->cart->get_cart( );
        $cart_item_keys   =  array_keys ( $cart_contents );
        $cart_item_count  =  count ( $cart_item_keys );

        // Do nothing if the cart is empty or has only one item
        if ( ! $cart_contents || $cart_item_count == 1 ) {
                return null;
        }

        // Multiple Items in cart
        $first_item                    =  $cart_item_keys[0];
        $first_item_id                 =  $cart_contents[$first_item]['product_id'];
        $first_item_top_category       =  get_product_top_level_category ( $first_item_id );
        $first_item_top_category_term  =  get_term ( $first_item_top_category, 'product_cat' );
        $first_item_top_category_name  =  $first_item_top_category_term->name;

        // Now we check each subsequent items top-level parent category
        foreach ( $cart_item_keys as $key ) {
                if ( $key  ==  $first_item ) {
                        continue;
                }
                else {
                        $product_id            =  $cart_contents[$key]['product_id'];
                        $product_top_category  =  get_product_top_level_category( $product_id );

                        if ( $product_top_category  !=  $first_item_top_category ) {
                                $woocommerce->cart->set_quantity ( $key, 0, true );
                                $restrict_categories  =  1;
                        }
                }
        }

        // code to display the message or warning only once for any user
        if ( isset ( $restrict_categories ) ) {
                echo '<p class="woocommerce-error">You can place order from one category at a time. </p>';
                //add your code for redirection here
                wp_redirect( $location, $status );
                                exit;
        }
}
?>

希望有所帮助!