Search code examples
phpwordpresswoocommercehook-woocommerce

Woocommerce: redirect hook overruled by error


In Wordpress/Woocommerce when clicking an order button, I would like it to skip the basket and immediately go to checkout. To this end, I implemented the following hook:

add_filter('add_to_cart_redirect', 'cw_redirect_add_to_cart');
function cw_redirect_add_to_cart() {
    global $woocommerce;
    $cw_redirect_url_checkout = $woocommerce->cart->get_checkout_url();
    return $cw_redirect_url_checkout;
}

This works. However, in the scenario that the user already has the product in their basket and clicks on the order button, this would normally produce an error message "You cannot add another productname to your basket", which would be displayed on the basket page. But with the code snippet, in this scenario it just refreshes the page where the user clicked the order button and nothing happens. A user will not understand why the button doesn't work (only if they would manually type in the basket url, they will see the error message).

How, in this scenario, can I still redirect to the checkout page?


Solution

  • The hook add_to_cart_redirect you are using is deprecated from version 3.0.0 as the get_checkout_url method is deprecated from version 2.5.

    The updated function can be found here: Woocommerce add to cart button redirect to checkout

    Your problem is related to the woocommerce_add_to_cart_redirect hook not being executed in case there are any error notices. Below you will find the part of the code extracted from the WooCommerce source code:

    // If we added the product to the cart we can now optionally do a redirect.
    if ( $was_added_to_cart && 0 === wc_notice_count( 'error' ) ) {
        $url = apply_filters( 'woocommerce_add_to_cart_redirect', $url, $adding_to_cart );
    
        if ( $url ) {
            wp_safe_redirect( $url );
            exit;
        } elseif ( 'yes' === get_option( 'woocommerce_cart_redirect_after_add' ) ) {
            wp_safe_redirect( wc_get_cart_url() );
            exit;
        }
    }
    

    So to fix the problem you can find a solution here.
    The post includes a Fix for "Sold Individually" Products section that answers your question.