1
votes

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.

2

2 Answers

1
votes

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.

0
votes

Did not you think about use the

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