Search code examples
phpwordpresswoocommercee-commercecart

How to skip cart page on woocomerce for certain products only?


I added this to my functions.php file :

add_filter ('woocommerce_add_to_cart_redirect', 'woo_redirect_to_checkout');
function woo_redirect_to_checkout() {
$checkout_url = WC()->cart->get_checkout_url();
return $checkout_url;
}

But now, all the products are re-directing strait to check-out. I would like to have this option only in one product. Is that a way I can add a product ID to that same filer?

Thank you!


Solution

  • You need to get the product when It is just added to cart , then check if for this product you want to redirect the cart page to checkout page . You need to change $desire_product = 'certain_product'; line on below code and It will definitely work.

    add_filter( 'woocommerce_add_to_cart_redirect', 'woo_redirect_checkout' );
    
    function woo_redirect_checkout() {
        global $woocommerce;
        $desire_product = 'certain_product';
        //Get product ID
        $product_id = (int) apply_filters( 'woocommerce_add_to_cart_product_id', $_POST['add-to-cart'] );
    
        //Check if current product is subscription
        if ( $product_id == $desire_product ){
            $checkout_url = $woocommerce->cart->get_checkout_url();
            return $checkout_url;
            exit;
        } else {
            $cart_url = $woocommerce->cart->get_cart_url();
            return $cart_url;
            exit;
        }
    }