Redirect to Checkout when a Product has been Added to the Cart
Step 1. Disable AJAX add to cart buttons
Sponsored ads:
Step 2. Change text on add to cart buttons
/*
* Change button text on Product Archives
*/
add_filter( 'woocommerce_loop_add_to_cart_link', 'misha_add_to_cart_text_1' );
function misha_add_to_cart_text_1( $add_to_cart_html ) {
return str_replace( 'Add to cart', 'Buy now', $add_to_cart_html );
}
/*
* Change button text on product pages
*/
add_filter( 'woocommerce_product_single_add_to_cart_text', 'misha_add_to_cart_text_2' );
function misha_add_to_cart_text_2( $product ){
return 'Buy now';
}
/*
* Change button text on Product Archives
*/
add_filter( 'woocommerce_product_add_to_cart_text', 'misha_add_to_cart_text_1', 10, 2 );
function misha_add_to_cart_text_1( $text, $product ){
return $product->is_purchasable() && $product->is_in_stock() ? 'Buy Now' : 'Read more';
}
Step 3. Redirect to Checkout Page
add_filter( 'woocommerce_add_to_cart_redirect', 'misha_skip_cart_redirect_checkout' );
function misha_skip_cart_redirect_checkout( $url ) {
return wc_get_checkout_url();
}
Function wc_get_checkout_url()
returns the current URL of your checkout page. I know, you can obtain your checkout page URL directly with the help of get_permalink()
and get_option()
functions. The checkout page ID is stored in wp_options
under woocommerce_checkout_page_id
key by the way.
But I recommend to use wc_get_checkout_url()
in any way.
Fix for “Sold Individually” Products
Certainly we do not want this message do be shown, do we?
My recommendation is simple – hook the add to cart url with woocommerce_product_add_to_cart_url
, check if the product is already in the cart and if so, replace the add to cart url with the checkout url. Easy peasy
add_filter( 'woocommerce_product_add_to_cart_url', 'misha_fix_for_individual_products', 10, 2 );
function misha_fix_for_individual_products( $add_to_cart_url, $product ){
if( $product->get_sold_individually() // if individual product
&& WC()->cart->find_product_in_cart( WC()->cart->generate_cart_id( $product->id ) ) // if in the cart
&& $product->is_purchasable() // we also need these two conditions
&& $product->is_in_stock() ) {
$add_to_cart_url = wc_get_checkout_url();
}
return $add_to_cart_url;
}
Sponsored ads:
Step 4. Remove “The product has been added to your cart” message
add_filter( 'wc_add_to_cart_message_html', 'misha_remove_add_to_cart_message' );
function misha_remove_add_to_cart_message( $message ){
return '';
}
If you Found this article interesting or Need help, please comment below…
Cheers! Ludovic
Credits
- Credits to https://rudrastyh.com/
- Elementor
- WordPress
You might be interested in hiding Google ReCaptcha badge on your website. Here is a guide on how to do it right.