Woocommerce-只允许特殊类别购物车中的单个项目

时间:2019-02-25 15:40:32

标签: php wordpress woocommerce

我有一个“预购商品”类别,如果购物车中已有预购商品,我曾使用here中的代码来停止添加其他任何产品类别。

我也想禁止“预购”类别中的多个不同产品,但仍然允许多个相同的产品。

当前,我正在我的子主题的functions.php中运行以下内容:

add_action( 'woocommerce_check_cart_items', 'checking_cart_items' );
function checking_cart_items() {

global $woocommerce; // if needed, not sure (?)
$special = false;
$catx = 'preorder';
$number_of_items = sizeof( WC()->cart->get_cart() );

if ( $number_of_items > 0 ) {

    // Loop through all cart products
    foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
        $item = $values['data'];
        $item_id = $item->id;

        // detecting if 'preorder' item is in cart
        if ( has_term( $catx, 'product_cat', $item_id ) ) {
            if (!$special) {
                $special = true;
            }
        }
    }

    // Re-loop through all cart products
    foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
        $item = $values['data'];
        $item_id = $item->id;

        if ( $special ) // there is a 'preorder' item in cart
        { 
            if ( $number_of_items == 1 ) { // only one 'preorder' item in cart
                if ( empty( $notice ) ){
                    $notice = '1';
                }
            }
            if ( $number_of_items >= 2 ) { // 'preorder' item + other categories items in cart

                // removing other categories items from cart
                if ( !has_term( $catx, 'product_cat', $item_id ) ) {
                    WC()->cart->remove_cart_item( $cart_item_key ); // removing item from cart
                    if ( empty( $notice ) || $notice == '1' ){
                        $notice = '2';
                    }
                }
            }
        } else { // Only other categories items

            if ( empty( $notice ) ){
                $notice = '3';
            }
        }
    }

    // Firing woocommerce notices
    if ( $notice == '1' ) { // message for an 'preorder' item only (alone)
        wc_add_notice( sprintf( '<p class="woocommerce-error">One pre-order item in cart</p>' ), 'success' );
    } elseif ( $notice == '2' ) { // message for an 'preorder' item and other ones => removed other ones 
        wc_add_notice( sprintf( '<p class="woocommerce-error">Pre-order items must be purchased individually. Other items have been removed.</p>' ), 'error' );
    } elseif ( $notice == '3' ) { // message for other categories items (if needed)
        wc_add_notice( sprintf( '<p class="woocommerce-error">bla bla bla NOT category X in the cart</p>' ), 'success' );
    }
}

我是否可以使用类似的循环来检查购物车中的多个“预购”商品并将其删除?

0 个答案:

没有答案