Woocommerce在短代码中显示自定义购物车总数



我正试图在一个短代码中显示一个wooccommerce自定义购物车总额。该代码获取购物车总额,然后减去"葬礼类型新"类别中任何产品的价格,以显示小计。这是代码:

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>';
}

$支出显示良好,但是$小计显示0,所以我认为部分$小计=$total-$deployment;可能有问题;?

非常感谢您的帮助。

您的代码中有很多错误,比如:

  • 在一个短代码中,显示从不被回显而是被返回
  • CCD_ 1 CCD_,_要在购物车项目上检查产品类别,请始终使用$cart_item['product_id']

所以改为尝试:

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]');

它应该更好地工作。

你没有想过使用吗

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

最新更新