Ad
Additional Add To Cart Button Redirecting To Checkout On WooCommerce Loop
I need a button on the WooCommerce archive that adds the product to cart and that re-directs the customer to the checkout. I call it "Buy and Checkout".
I'm hooking into the archive by using the woocommerce_after_shop_loop_item
action and I have defined the global $product;
argument.
I then get the product ID and I then define the add to cart url (atc_url
argument).
Problem is, when clicking on add to cart, the product is not added.
This is my code so far and I'm not really sure what's wrong here.
add_action( 'woocommerce_after_shop_loop_item', 'buy_checkout_on_archive', 20 );
function buy_checkout_on_archive(){
global $product;
$pid = $product->get_id();
$atc_url = wc_get_checkout_url().'?add-to-cart='.$pid;
$button_class = 'loop-checkout-btn';
$button_text = __('Buy & Checkout', 'woocommerce');
if ($product->is_type('simple')){
echo '<a href="'.$atc_url.'" class="'.$button_class.'">'.$button_text.'</a>';
}
}
Ad
Answer
The following will do the trick, adding a custom add to cart button on WooCommerce archives that redirect to checkout after adding the product to cart:
add_action( 'woocommerce_after_shop_loop_item', 'buy_checkout_on_archive', 20 );
function buy_checkout_on_archive(){
global $product;
if ( $product->is_type('simple') ){
$product_id = $product->get_id();
$button_url = '?addtocart='.$product_id;
$button_class = 'button loop-checkout-btn';
$button_text = __('Buy & Checkout', 'woocommerce');
echo '<a href="'.$button_url.'" class="'.$button_class.'">'.$button_text.'</a>';
}
}
add_action( 'template_redirect', 'addtocart_on_archives_redirect_checkout' );
function addtocart_on_archives_redirect_checkout(){
if( isset( $_GET['addtocart'] ) && $_GET['addtocart'] > 0 ) {
WC()->cart->add_to_cart( intval($_GET['addtocart']) );
// Checkout redirection
wp_safe_redirect( wc_get_checkout_url() );
exit;
}
}
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
Ad
source: stackoverflow.com
Related Questions
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS create a multi select Form field
- → October CMS - Conditionally Load a Different Page
- → How to disable assets combining on development in OctoberCMS
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → OctoberCms component: How to display all ID(items) instead of sorting only one ID?
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?
Ad