简体   繁体   中英

Woocommerce displaying custom cart total in a shortcode

I am trying to display a woocommerce custom cart total amount within a shortcode. The code takes the cart total and then substracts the price of any products within the 'funeral-types-new' category to display a subtotal. Here is the code:

add_shortcode( 'quote-total', 'quote_total' );
function quote_total(){   

$total = $woocommerce->cart->total; 

    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
    $_product   = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );

        if ( has_term( 'funeral-types-new', 'product_cat', $_product->id) ) {
            $disbursement = apply_filters( 'woocommerce_cart_item_price', WC()->cart->get_product_price( $_product ), $cart_item, $cart_item_key );
        }
}

$subtotal = $total-$disbursement;

echo '<div>'.$subtotal.'</div><div> + '.$disbursement.'</div>';

}

The $disbursement displays fine however the $subtotal displays 0 so I think something may be wrong with the section $subtotal = $total-$disbursement;?

Any help much appreciated.

There are many mistakes in your code, like:

  • in a shortcode the display is never echoed but returned,
  • WC_Cart get_product_price() method display the formatted product price for display only, _ To check for a product category on cart items always use $cart_item['product_id'] instead...

So try instead:

add_shortcode( 'quote-total', 'get_quote_total' );
function get_quote_total(){
    $total        = WC()->cart->total;
    $disbursement = 0; // Initializng
    
    // Loop through cart items
    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
        if ( has_term( array('funeral-types-new'), 'product_cat', $cart_item['product_id'] ) ) {
            $disbursement += $cart_item['line_total'] + $cart_item['line_tax'];
        }
    }
    
    $subtotal = $total - $disbursement;
    
    return '<div>'.wc_price($subtotal).'</div><div> + '.wc_price($disbursement).'</div>';
}

// USAGE: [quote-total] 
//    or: echo do_shortcode('[quote-total]');

It should better work.

你有没有想过使用

WC()->cart->get_subtotal();

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