简体   繁体   中英

Woocommerce cart amount AJAX shortcode

I've made a snippet to display the cart total in a shortcode. I use it at the checkout page (created a multistep checkout) before order validation.

add_shortcode( 'quote-total', 'get_quote_total' );
function get_quote_total(){
    $total        = WC()->cart->total;
    
    return '<div>'.wc_price($total).'</div>';
}

// USAGE: [quote-total]

Now, I would like to use AJAX to make the amount change when there is new data, like shipping. Do you know how can I achieve it?

You should add some selector (eg class name) to your element:

return '<div class="step-cart-total">'.wc_price($total).'</div>';

Then you should be able to utilize woocommerce_add_to_cart_fragments filter like so:

function custom_woocommerce_add_to_cart_fragments( $fragments ) {

    // Ajaxify checkout step cart total
    ob_start();
    $total = WC()->cart->total;    
    echo '<div class="step-cart-total">'.wc_price($total).'</div>';    
    $fragments['.step-cart-total'] = ob_get_clean();

    return $fragments;
}
add_filter( 'woocommerce_add_to_cart_fragments', 'custom_woocommerce_add_to_cart_fragments');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM