Reputation: 35
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.
Upvotes: 1
Views: 4698
Reputation: 11
This worked for me: (Be sure to grab the last line under the code block... It separated it for some reason.)
<?php
function working_cart_total_shortcode() {
if (!function_exists('WC') || !isset(WC()->cart)) {
return 'Cart not initialized';
}
$total = 0;
$cart_items = WC()->cart->get_cart();
foreach ($cart_items as $cart_item) {
$product = $cart_item['data'];
$price = floatval($product->get_price());
$quantity = intval($cart_item['quantity']);
$item_total = $price * $quantity;
$total += $item_total;
}
// Simple numeric display that we know works
return sprintf(
'<div class="working-cart-total"> $%.2f</div>',
$total
);
}
add_shortcode('working_cart_total', 'working_cart_total_shortcode');
?>
Upvotes: 1
Reputation: 254363
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:
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.
Upvotes: 1