【问题标题】:Remove other products if certain product category is present on WooCommerce checkout如果 WooCommerce 结帐中存在某些产品类别,请删除其他产品
【发布时间】:2022-01-10 21:02:01
【问题描述】:

我正在为客户创建一个登录页面,其中包含类别为landing-page 的特定产品。

我希望在购物车中出现 landing-page 类别时删除当前在购物车页面上的其他产品。

这里是sn-p。现在,由于$woocommerce->cart->empty_cart(),它会删除其中的所有产品。

add_action('woocommerce_checkout_before_customer_details', 'check_if_landing_page_category_is_on_cart');
function check_if_landing_page_category_is_on_cart() {
    
    global $woocommerce;
    $categories   = array('landing-page');
    $has_category = false;
    
    foreach ( WC()->cart->get_cart() as $cart_item ) {
        // Check for product categories
        if ( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ) {
            
            $woocommerce->cart->empty_cart();
            $has_category = true;
            break;
        }
    }
    
    if ( $has_category ) { 
        ?>
            <style>
                .coupon-form {
                    display: none;
                }
            </style>
        <?php
    }
}

有什么建议吗?

【问题讨论】:

    标签: wordpress woocommerce product hook-woocommerce checkout


    【解决方案1】:

    你可以用WC_Cart::remove_cart_item()对面WC_Cart::empty_cart()

    所以你得到:

    function action_woocommerce_checkout_before_customer_details() {
        // Add categories. Multiple can be added, separated by a comma
        $categories = array( 'landing-page' );
        
        // Initialize
        $cart_item_keys = array();
        $has_category = false;
        
        // WC Cart NOT null
        if ( ! is_null( WC()->cart ) ) {
            // Loop through cart items
            foreach ( WC()->cart->get_cart_contents() as $cart_item_key => $cart_item ) {
                // Get product id
                $product_id = $cart_item['product_id'];
                
                // NOT certain category     
                if ( ! has_term( $categories, 'product_cat', $product_id ) ) {
                    // Push to array
                    $cart_item_keys[] = $cart_item_key;
                } else {
                    $has_category = true;
                }
            }
            
            // NOT empty & has category is true
            if ( ! empty ( $cart_item_keys ) && $has_category ) {
                // Loop through all cart item keys that do not contain the category
                foreach ( $cart_item_keys as $cart_item_key ) {
                    // Remove product from cart
                    WC()->cart->remove_cart_item( $cart_item_key ); 
                }
            }
        }
    }
    add_action( 'woocommerce_checkout_before_customer_details', 'action_woocommerce_checkout_before_customer_details', 10, 0 );
    

    【讨论】:

      猜你喜欢
      • 2022-01-20
      • 1970-01-01
      • 2021-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-06
      • 2021-01-09
      • 2020-10-15
      相关资源
      最近更新 更多