Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save FrancoStino/69f67468b9dbadb74cdfe540180c108d to your computer and use it in GitHub Desktop.
Save FrancoStino/69f67468b9dbadb74cdfe540180c108d to your computer and use it in GitHub Desktop.
Add a quick buy now checkout button into single product page and shop loop item - Woocommerce
<?php
/*
* Add a quick buy now checkout button in woocommerce into single product page and shop loop item
*/
add_action( 'woocommerce_after_shop_loop_item', 'add_custom_addtocart_and_checkout', 10 );
add_action( 'woocommerce_after_add_to_cart_button', 'add_custom_addtocart_and_checkout' );
function add_custom_addtocart_and_checkout() {
global $product;
$addtocart_url = wc_get_checkout_url().'?add-to-cart='.$product->get_id();
$button_class = 'single_add_to_cart_button button py-2';
$button_text = __("Paga ora", "woocommerce");
if ( ! $product->is_purchasable() || ! $product->is_in_stock() ) {
return;
}
if( $product->is_type( 'simple' )) :
?>
<script>
jQuery(function($) {
var url = '<?php echo $addtocart_url; ?>',
qty = 'input.qty',
button = 'single_add_to_cart_button button py-2';
// On input/change quantity event
$(qty).on('input change', function() {
$(button).attr('href', url + '&quantity=' + $(this).val() );
});
});
</script>
<?php
elseif( $product->is_type( 'variable' ) ) :
$addtocart_url = wc_get_checkout_url().'?add-to-cart=';
?>
<script>
jQuery(function($) {
var url = '<?php echo $addtocart_url; ?>',
vid = 'input[name="variation_id"]',
pid = 'input[name="product_id"]',
qty = 'input.qty',
button = 'single_add_to_cart_button button py-2';
// Once DOM is loaded
setTimeout( function(){
if( $(vid).val() != '' ){
$(button).attr('href', url + $(vid).val() + '&quantity=' + $(qty).val() );
}
}, 300 );
// On input/change quantity event
$(qty).on('input change', function() {
if( $(vid).val() != '' ){
$(button).attr('href', url + $(vid).val() + '&quantity=' + $(this).val() );
}
});
// On select attribute field change event
$('.variations_form').on('change blur', 'table.variations select', function() {
if( $(vid).val() != '' ){
$(button).attr('href', url + $(vid).val() + '&quantity=' + $(qty).val() );
}
});
});
</script>
<?php
endif;
echo '<a style="display: flex !important; gap: 20px; justify-content: center; align-items: center; margin-top: 20px" href="'.$addtocart_url.'" class="'.$button_class.'"><i class="las la-credit-card la-lg d-none d-sm-inline"></i>'.$button_text.'</a>';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment