Skip to content
Advertisement

How to make a redirection to checkout on a custom add to cart button in WooCommerce

I’m using WooCommerce and added the following code to functions.php:

add_filter( 'woocommerce_product_add_to_cart_url', 'custom_fix_for_individual_products', 10, 2 );

function custom_fix_for_individual_products( $add_to_cart_url, $product ){
    $add_to_cart_url = wc_get_checkout_url();
    return $add_to_cart_url;
}

What I would expect is that when a user adds a product to their basket: this code will redirect the user to the checkout page without actually adding the product to the basket. However, it still adds the product to the basket. What is wrong with this code?

Background: I’m using Uncaught Error: Call to a member function generate_cart_id() on null answer code but it doesn’t work correctly for the above line, which is why I’m now working with only that line. There’s no error in the server logs.

Advertisement

Answer

Based on your comment, to get a redirection to checkout page for a custom add to cart button, you could change the link to something like https://example.com/checkout/?add-to-cart=99 where 99 is the product Id that you want to add to cart.

So the code for your custom add to cart button link will be like (where 99 is the product Id):

$product_id = 99;
$url        = wc_get_checkout_url() . '?add-to-cart=' . $product_id;
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement