【问题标题】:Woocommerce displaying custom cart total in a shortcodeWoocommerce 在简码中显示自定义购物车总数
【发布时间】:2020-09-11 15:56:59
【问题描述】:

我正在尝试在短代码中显示 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; 部分可能有问题?

非常感谢任何帮助。

【问题讨论】:

    标签: php wordpress woocommerce cart shortcode


    【解决方案1】:

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

    • 在简码中,显示永远不会回显,而是返回,
    • WC_Cart get_product_price() method 显示格式化的产品价格仅用于显示, _ 要检查购物车商品上的产品类别,请始终使用 $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]');
    

    它应该更好地工作。

    【讨论】:

      【解决方案2】:

      你没有考虑过使用

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-12-10
        • 1970-01-01
        • 1970-01-01
        • 2021-01-16
        • 1970-01-01
        • 1970-01-01
        • 2018-08-20
        • 2019-04-21
        相关资源
        最近更新 更多