仅在特定页面上从 WooCommerce 购物车中删除特定产品

Remove specific product from WooCommerce cart only on a specific page

当客户登陆特定页面时,我正在尝试删除购物车中的特定产品。

页面 ID 为 8688,产品 ID 为 8691 (该产品是可变产品,所以我想确定无论购物车中的变化如何,如果购物车中的整个产品都被删除)

这是我到目前为止想出的:

add_action( 'template_redirect', 'remove_product_from_cart' );
function remove_product_from_cart() {
       if( WC()->cart->is_empty() ) return;
    if( ! is_page( 8688 ) ) return;
    if ( is_admin() ) return;
    
   $product_id = 8691;
   $product_cart_id = WC()->cart->generate_cart_id( $product_id );
   $cart_item_key = WC()->cart->find_product_in_cart( $product_cart_id );
   if ( $cart_item_key ) WC()->cart->remove_cart_item( $cart_item_key );
}

但这并没有真正起作用,但我感到完全迷失了。感谢所有帮助。

改为尝试以下重新访问的代码:

add_action( 'template_redirect', 'remove_product_from_cart' );
function remove_product_from_cart() {
    if( is_admin() || WC()->cart->is_empty() ) {
        return; // Exit
    }

    if ( is_page( 8688 ) ) {
        $remove_item_key     = false;
        $targeted_product_id = 8691;

        // Loop though cart items
        foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
            if ( in_array( $targeted_product_id, array( $cart_item['product_id'], $cart_item['variation_id'] ) ) ) {
                $remove_item_key = $cart_item_key;
                break; // Stop the loop
            }
        }

        if ( $remove_item_key ) {
            WC()->cart->remove_cart_item( $remove_item_key );
        }
    }
}

代码进入您的活动子主题(或活动主题)的 functions.php 文件。已测试并有效。