Skip to content

Instantly share code, notes, and snippets.

@tdmrhn
Last active July 10, 2024 22:14
Show Gist options
  • Save tdmrhn/69ed902491454fe7df37e841c7821156 to your computer and use it in GitHub Desktop.
Save tdmrhn/69ed902491454fe7df37e841c7821156 to your computer and use it in GitHub Desktop.
Blocksy Add Ajax Quantity to Archive Cards
<?php
add_filter( 'woocommerce_loop_add_to_cart_link', function ( $html, $product ) {
if ( $product && $product->is_type( 'simple' ) && $product->is_purchasable() && $product->is_in_stock() && ! $product->is_sold_individually() ) {
$class = implode( ' ', array_filter( array(
'button',
'product_type_' . $product->get_type(),
$product->is_purchasable() && $product->is_in_stock() ? 'add_to_cart_button' : '',
$product->supports( 'ajax_add_to_cart' ) ? 'ajax_add_to_cart' : '',
) ) );
$html = sprintf( '%s%s<a rel="nofollow" href="%s" data-quantity="%s" data-product_id="%s" data-product_sku="%s" class="%s ct-cart-actions">%s</a>%s',
'<form class="cart">',
woocommerce_quantity_input( array(), $product, false ),
esc_url( $product->add_to_cart_url() ),
esc_attr( isset( $quantity ) ? $quantity : 1 ),
esc_attr( $product->get_id() ),
esc_attr( $product->get_sku() ),
esc_attr( isset( $class ) ? $class : 'button' ),
esc_html( $product->add_to_cart_text() ),
'</form>'
);
}
return $html;
}, 10, 2 );
add_action( 'wp_footer' , function (){
if( is_home() || is_front_page() || is_shop() || is_product_category() || is_product_tag() ) { ?>
<script type='text/javascript'>
jQuery( document ).ready( function( $ ) {
$( document ).on( 'change', '.quantity .qty', function() {
$( this ).parent( '.quantity' ).next( '.add_to_cart_button' ).attr( 'data-quantity', $( this ).val() );
});
});
jQuery(function($) {
$(".add_to_cart_button.product_type_simple").on('click', function() {
var $button = $(this);
$button.data('quantity', $button.parent().find('input.qty').val());
});
$(document.body).on("adding_to_cart", function() {
$("a.added_to_cart").remove();
});
});
</script>
<?php }
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment