Ottenere il totale del carrello di WooCommerce via AJAX è un'operazione semplice in WordPress.
Definiamo la nostra action AJAX in functions.php
:
function my_wc_get_cart_total() {
global $woocommerce;
$total = $woocommerce->cart->get_cart_total();
echo $total;
exit();
}
add_action( 'wp_ajax_my_wc_get_cart_total', 'my_wc_get_cart_total' );
add_action( 'wp_ajax_nopriv_my_wc_get_cart_total', 'my_wc_get_cart_total' );
Quindi con jQuery:
(function( $ ) {
$.fn.cartTotal = function( options ) {
options = $.extend({
url: "http://" + location.host + "/wp-admin/admin-ajax.php",
action: "my_wc_get_cart_total"
}, options);
function getCartTotal( element ) {
$.when( $.get( options.url, { action: options.action } ) ).
done(function( resp ){
element.text( resp );
});
}
return this.each(function() {
var $element = $( this );
getCartTotal( $element );
});
};
$(function() {
if( $( "#cart-total" ).length ) {
$( "#cart-total" ).cartTotal();
}
});
})( jQuery );