允许从 Woocommerce 中的购物车中删除自动添加的产品

Allow to remove product automatically added from cart in Woocommerce

在 Woocommerce 中,我使用 this official code snippet 在客户访问我的网站时自动将产品添加到购物车:

add_action( 'template_redirect', 'add_product_to_cart' );
function add_product_to_cart() {
    if ( ! is_admin() ) {
        $product_id = 1234; //replace with your own product id
        $found = false;
        //check if product already in cart
        if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
            foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
                $_product = $values['data'];
                if ( $_product->get_id() == $product_id )
                    $found = true;
            }
            // if product not found, add it
            if ( ! $found )
                WC()->cart->add_to_cart( $product_id );
        } else {
            // if no products in cart, add it
            WC()->cart->add_to_cart( $product_id );
        }
    }
}

它工作正常并将产品添加到购物车。

但我希望客户提供选项 以将此商品从购物车中删除 如果他们不想要它。但实际上该产品无法删除。

我怎样才能使产品自动添加到购物车可移除?

试试这个代码。

add_action( 'template_redirect', 'add_product_to_cart' );
function add_product_to_cart() {
    if ( ! is_admin()  && !is_cart() && !is_checkout()) {
        $product_id = 1234; //replace with your own product id
        $found = false;
        //check if product already in cart
        if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
            foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
                $_product = $values['data'];
                if ( $_product->get_id() == $product_id )
                    $found = true;
            }
            // if product not found, add it
            if ( ! $found )
                WC()->cart->add_to_cart( $product_id );
        } else {
            // if no products in cart, add it
            WC()->cart->add_to_cart( $product_id );
        }
    }
}