3
votes

I would like to bypass cart page and redirect user to checkout page for a few products.

I have created the add to cart link for the product <a href="http://example.net/?add-to-cart=1461">Product Name</a>

And I have the code below

add_filter( 'woocommerce_add_to_cart_redirect', 'woo_redirect_checkout' );

function woo_redirect_checkout() {
    global $woocommerce;
    $desire_product = 1461;
    //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;
    }
}

from How to skip cart page on woocomerce for certain products only?. But the url redirect me to homepage instead. Just wondering where is the issue,

I have unchecked the add to cart behaviour at woocommerce settings as well.

Thanks in advance.

1

1 Answers

1
votes

I chose another approach and a WordPress hook instead of woocommerce. This is based on this answer: WooCommerce - Skip cart page redirecting to checkout page

This is that code:

 function skip_cart_page_redirection_to_checkout() {

    // desired product id redirection
    $product_id = 1461;
    $items_ids = array();

    // Get all items IDs that are in cart
    foreach( WC()->cart->get_cart() as $item ) {
        $items_ids[] = $item['product_id'];
    }

    // If is cart page and the desired peoduct is in cart => redirect to checkout.
    if( is_cart() && in_array($product_id, $items_ids) )
        // WooCommerce 3.0 compatibility added
        if ( version_compare( WC_VERSION, '2.7', '<' ) ) {
            wp_redirect( WC()->cart->get_checkout_url() ); // Older than 3.0
        } else {
            wp_redirect( wc_get_checkout_url() ); // 3.0+ (Thanks to helgatheviking)
        }

}
add_action('template_redirect', 'skip_cart_page_redirection_to_checkout');

This code goes in function.php file of your active child theme (or theme) or also in any plugin file.

The code is tested and fully functional.