skip to Main Content

From my Woocommerce cart page, I would like to automatically redirect users to the checkout page when they click the “Update Cart” button, after the update_cart_action() function has finished executing.

The last lines of the WC update_cart_action() function handle redirects:

if ( ! empty( $_POST['proceed'] ) ) {
    wp_safe_redirect( wc_get_checkout_url() );
    exit;
} elseif ( $cart_updated ) {
    wc_add_notice( __( 'Cart updated.', 'woocommerce' ), apply_filters( 'woocommerce_cart_updated_notice_type', 'success' ) );
    $referer = remove_query_arg( array( 'remove_coupon', 'add-to-cart' ), ( wp_get_referer() ? wp_get_referer() : wc_get_cart_url() ) );
    wp_safe_redirect( $referer );
    exit;
}

I tried assigning a value to $_POST[‘proceed’] to call wc_get_checkout_url(), like:

function mytheme_trigger_proceed_to_checkout( $cart_updated ) {

    $_POST['proceed'] = true;

    return $cart_updated;
}
add_filter( 'woocommerce_update_cart_action_cart_updated', 'mytheme_trigger_proceed_to_checkout', 10, 1 );

But instead of redirecting to my checkout url, I am redirected to the cart url with a blank page. Editing the WC plugin code directly got the same result.

How can I redirect to the checkout url after the cart has finished updating?

2

Answers


  1. I don’t have exact code ready with me yet, but I had done something similar in past.

    Try to hit something like below on $cart_updated

    function my_custom_add_to_cart_redirect( $url ) {
        $url = WC()->cart->get_checkout_url();
        // $url = wc_get_checkout_url(); // since WC 2.5.0
        return $url;
    }
    add_filter( 'woocommerce_add_to_cart_redirect', 'my_custom_add_to_cart_redirect' );
    
    Login or Signup to reply.
  2. Add the follows code snippet in your active theme’s functions.php to do the above –

    add_action( 'wp_footer', 'wc_modify_update_cart_totals' );
    function wc_modify_update_cart_totals() {
        ?>
        <script type="text/javascript">
            (function( $ ) { 
                $( document ).on( 'updated_cart_totals', function( event ) { 
                    window.location.href = '<?php echo wc_get_checkout_url(); ?>';
                } );
            } )( jQuery );
        </script>
        <?php
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search