WooCommerce php add_to_cart

Why complicated if you can make it easy?

I just searched the internet for a quick fix on how to quickly write an ajax function to put a product in a shopping cart in WooCommerce. Why do people make it so complicated? In the end, I wrote it myself and would like to quickly share the functions with you:

add_action( 'wp_ajax_nopriv_product_tile_add_to_cart', 'product_tile_add_to_cart' );
add_action( 'wp_ajax_product_tile_add_to_cart', 'product_tile_add_to_cart' );

function product_tile_add_to_cart(){
	$ret = WC()->cart->add_to_cart($_POST['product_id']);
	echo json_encode( $ret ? true : false );
	die();
}
$(document).on('click tap', '.single-product-tile .product-hover .product-hover-single', function(event) {
	event.preventDefault();
	event.stopPropagation();
	jQuery.ajax({
		url : injected.ajax_url,
		type : 'post',
		data : {
			action : 'product_tile_add_to_cart',
			product_id : $(this).closest('.single-product-tile').attr('productid')
		},
		success : function( response ) {
			r = JSON.parse(response);
			console.log( r );

			// console.log(response);

		}
	});
});

If you want you can protect this function with a nonce variable.

Good night and see you tomorrow!

Topics

jQuery php technology WordPress

Beitrag teilen

WhatsApp it

Folgen Sie uns