Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/wordpress/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 仅在特定页面上从WooCommerce购物车中删除特定产品_Php_Wordpress_Woocommerce_Product_Cart - Fatal编程技术网

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

Php 仅在特定页面上从WooCommerce购物车中删除特定产品,php,wordpress,woocommerce,product,cart,Php,Wordpress,Woocommerce,Product,Cart,我试图删除一个特定的产品,如果它在购物车中,当客户在一个特定的页面上着陆 页面ID是8688,产品ID是8691(此产品是一个可变产品,因此我想确保无论购物车中的变化如何,如果它在购物车中,整个产品都会被删除) 这就是我到目前为止的想法: add_action( 'template_redirect', 'remove_product_from_cart' ); function remove_product_from_cart() { if( WC()->cart->

我试图删除一个特定的产品,如果它在购物车中,当客户在一个特定的页面上着陆

页面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文件。测试和工作