Woocommerce:访问特定页面后,将产品添加到购物车+删除

时间:2018-08-20 11:48:59

标签: php wordpress woocommerce cart

访问页面后,访问者将直接转到结帐页面。该产品现已添加到购物车。一切正常。

问题:如果访问者决定添加其他产品,并且喜欢删除此自动添加的产品,则应该可以。目前,该产品留在购物车中,无法删除。

我使用了以下代码:

    /**
 * Automatically add product to cart on visit
 */
add_action( 'template_redirect', 'add_product_to_cart' );
function add_product_to_cart() {
    if ( ! is_admin() ) {
        $product_id = 7766; //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 );
        }
    }
}

0 个答案:

没有答案