WooCommerce Ajax add to cart custom redirect

woocommerce cart redirect

If you want to redirect to a custom url after adding a product to cart you can achieve that pretty easily if you don’t have the Ajax functionality enabled. An example of that can be seen here.

What if you use Ajax

Using Ajax that’s a little bit harder to achieve but you can do that using by “fake” throwing an error as that is being handled directly by WooCommerce.

In the WooCommerce add-to-cart.js file you will see this piece of code:

if ( response.error && response.product_url ) {
   window.location = response.product_url;
   return;
}

You can use this to manipulate the behavior by hooking into “woocommerce_ajax_added_to_cart”.

add_action('woocommerce_ajax_added_to_cart', 'm_custom_redirect');

function m_custom_redirect( $product_id ) {

    // add your check if certain product should trigger the redirect
    if ( $product_id == 34 ) {

        // custom redirect url
        $custom_redirect_url = get_permalink(55);

        $data = array(
            'error'       => true,
            'product_url' => $custom_redirect_url
        );

        wp_send_json( $data );

        exit;

    }

}

This can be used in a variety of situations in which you want to suggest another product after a product has been added to the cart.