簡體   English   中英

Woocommerce 在短代碼中顯示自定義購物車總數

[英]Woocommerce displaying custom cart total in a shortcode

我正在嘗試在短代碼中顯示 woocommerce 自定義購物車總金額。 該代碼采用購物車總計,然后減去“葬禮類型-新”類別中任何產品的價格以顯示小計。 這是代碼:

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

}

$disbursement 顯示正常,但 $subtotal 顯示 0,所以我認為 $subtotal = $total-$disbursement; 部分可能有問題?

非常感謝任何幫助。

您的代碼中有很多錯誤,例如:

  • 在簡碼中,顯示永遠不會回顯,而是返回,
  • WC_Cart get_product_price()方法僅顯示格式化的產品價格以供顯示,_ 要檢查購物車項目上的產品類別,請始終使用 $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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM