I’m using this simple code to add a ‘buy now’ button on a single product page.
add_action( 'woocommerce_after_add_to_cart_button', 'add_content_after_addtocart' );
function add_content_after_addtocart() {
// get the current post/product ID
$current_product_id = get_the_ID();
// get the product based on the ID
$product = wc_get_product( $current_product_id );
// get the "Checkout Page" URL
$checkout_url = WC()->cart->get_checkout_url();
// run only on simple products
if( $product->is_type( 'simple' ) ) {
echo '<a href="'.$checkout_url.'?add-to-cart='.$current_product_id.'" class="mongo_single_add_to_cart_button button">Buy Now</a>';
}
}
This code effectively redirects to the checkout page and add the product to the cart, but I want to add two little features to it:
-
After clicking on the button, I want it to clear the cart before taking the action.
-
After adding the product to the cart, I want it to redirect users to ‘/checkout’ page. Right now it sends users on ‘checkout/?add-to-cart=3122’, which means that any refresh on the checkout page adds 1 product on the cart automatically.
Any advice?
2
Answers
Here is code for clear cart before add item
After adding the product to the cart, I want it to redirect users to ‘/checkout’ page. Right now it sends users on ‘checkout/?add-to-cart=3122’, which means that any refresh on the checkout page adds 1 product on the cart automatically.
add_filter( ‘woocommerce_add_to_cart_redirect’, ‘ji_redirect_checkout_after_add_to_cart’ );
function ji_redirect_checkout_after_add_to_cart() {
return wc_get_checkout_url();
}
Instead of using the
add-to-cart
param in your url, which will cause the product to be added (but also perform other actions in WooCommerce), you can use a custom url for your button and thetemplate_redirect
action hookThat way you get rid of the built-in functionality in WooCommerce and you can perform your own custom actions based on the GET parameters
So you get: