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
Answers
Did not you think about use the
There are many mistakes in your code, like:
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:
It should better work.