[英]Woocommerce displaying custom cart total in a shortcode
I am trying to display a woocommerce custom cart total amount within a shortcode.我正在尝试在短代码中显示 woocommerce 自定义购物车总金额。 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;? $disbursement 显示正常,但 $subtotal 显示 0,所以我认为 $subtotal = $total-$disbursement; 部分可能有问题?
Any help much appreciated.非常感谢任何帮助。
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... WC_Cart
get_product_price()
方法仅显示格式化的产品价格以供显示,_ 要检查购物车项目上的产品类别,请始终使用 $cart_item['product_id'] 代替...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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.