WordPress: aggiungere un prodotto al carrello di WooCommerce via AJAX

WordPress: aggiungere un prodotto al carrello di WooCommerce via AJAX

Aggiungere un prodotto al carrello di WooCommerce via AJAX è un'operazione semplice se si conoscono le API AJAX di WordPress.

Definiamo la nostra action AJAX in functions.php:


function my_wc_add_to_cart() {
	$product_id = (int) $_POST['pid']; // ID prodotto
	$qty = (int) $_POST['pqty']; // Quantità prodotto
	$output = 0;

	// Validazione
	if( filter_var( $product_id, FILTER_VALIDATE_INT ) && filter_var( $qty, FILTER_VALIDATE_INT ) ) {
		global $woocommerce;
		$pid = $product_id;
		$quantity = $qty;
		$variation_id = '';
		$variation = '';
		$cart_item_data = array();

		if( $woocommerce->cart->add_to_cart( $pid, $quantity, $variation_id, $variation, $cart_item_data ) ) {
			// Se l'azione ha avuto successo restituiamo l'ID del prodotto 
			$output = $product_id;
		}
	}

	echo $output;
	exit();

}

add_action( 'wp_ajax_my_wc_add_to_cart', 'my_wc_add_to_cart' );
add_action( 'wp_ajax_nopriv_my_wc_add_to_cart', 'my_wc_add_to_cart' );

Quindi impostiamo la marcatura del form di aggiunta al carrello:


<form action="" method="post" class="shop-cart" data-product="<?php the_ID(); ?>">
	<!--...-->
	<input type="text" class="qty" placeholder="Quantità" />
	<!--....-->
</form>

Aggiungiamo infine il codice jQuery:


(function( $ ) {
	$(function() {
		var $shopCart = $( ".shop-cart" );
		$shopCart.each(function() {
			var $form = $( this );
			$form.on( "submit", function( e ) {
				e.preventDefault();
				var url = "http://" + location.host + "/wp-admin/admin-ajax.php",
					data = {
						action: "my_wc_add_to_cart",
						pid: $form.data( "product" ),
						pqty: $( ".qty", $form ).val()
					};
				$.post( url, data, function( resp ) {
					var output = parseInt( resp, 10 );
					if( output > 0 ) {
						// Aggiunto con successo
					} else {
						// Errore
					}
					
				});
			});
		});
	});
	
})( jQuery );

Torna su