简体   繁体   中英

Get cart total including last added item in WooCommerce

In WooCommerce I'm trying to get the cart total when hooking into woocommerce_add_to_cart . That works, but the cart total returned is the total prior to the last added item. I want the updated total, to be able to display a notice regarding shipping costs.

Any idea how to achieve this?

My current code:

function oppsalg_add_to_cart() {
    global $woocommerce;

    // Limit
    $minimum_cart_total = 1000;

    // Cart value (Not including the last added item)
    $total = WC()->cart->subtotal;

    // Comparison
    if( $total < $minimum_cart_total ) {
        // Display notice
        wc_add_notice( sprintf( '<strong>Shipping is free above %s.</strong>'
            .'<br />Your total is %s. Perhaps you would like to add more items?',
            $minimum_cart_total,
            $total ),
        'notice' );
    }
}
add_action('woocommerce_add_to_cart', 'oppsalg_add_to_cart');

Here you go, just tested this solution on adding a single page product to the cart without AJAX. This won't modify the message you see when you change the cart quantity on the Cart page though via AJAX. Also you should make the shipping cost dynamic so that it's not hard coded like I have done below, that can be your homework to fix.

add_filter( 'wc_add_to_cart_message_html', 'modify_wc_add_to_cart_message_html', 10, 2 );

function modify_wc_add_to_cart_message_html( $message, $products ) {

    $minimum_cart_total = 100;
    $cart_total = WC()->cart->cart_contents_total;

    if( $cart_total < $minimum_cart_total ) {
        $message = sprintf( '<strong>Shipping is free above %s.</strong>'
                            .'<br />Your total is %s. Perhaps you would like to add more items?',
                            wc_price( $minimum_cart_total ),
                            wc_price( $cart_total )
                            );
    }

    return $message;
}

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