Ich habe eben im Internet nach einer schnellen Lösung gesucht, wie ich schnell eine Ajax Funktion schreiben kann, um ein Produkt in ein Warenkorb legen zu lassen. Wieso machen die Leute es sich so kompliziert? Im Endeffekt habe ich es selbst geschrieben und würde gerne mit euch die Funktionen schnell teilen:
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);
}
});
});
Wenn man möchte kann man diese Programmierung auch mit einer Nonce Variable absichern.
Gute Nacht und bis Morgen!