首页 > 解决方案 > 在 WooCommerce 中根据数量显示产品价格

问题描述

如何在 woocommerce 商店页面中显示基于 12 个数量的产品价格。

在此处输入图像描述

function sv_change_product_html( $price_html, $product ) {
    $unit_price = get_post_meta( $product->id, 'unit_price', true );
    if ( ! empty( $unit_price ) ) {
        $price_html = '<span class="amount">' . wc_price( $unit_price ) . ' inc GST per bottle</span>'; 
    }

    return $price_html;
}

add_filter( 'woocommerce_get_price_html', 'sv_change_product_html', 10, 2 );


function sv_change_product_price_cart( $price, $cart_item, $cart_item_key ) {

      $unit_price = get_post_meta( $cart_item['product_id'], 'unit_price', true );
    if ( ! empty( $unit_price ) ) {
        $price = wc_price( $unit_price ) . ' inc GST per bottle';   
    }
    return $price;

}   

add_filter( 'woocommerce_cart_item_price', 'sv_change_product_price_cart', 10, 3 );

标签: phpwordpresswoocommerceproductcart

解决方案


自 WooCommerce 3 以来,您的代码有点过时(而且您的问题有点不清楚)......尝试以下操作:

add_filter( 'woocommerce_get_price_html', 'displayed_product_unit_price', 10, 2 );
function displayed_product_unit_price( $price_html, $product ) {
    if ( $unit_price = $product->get_meta( 'unit_price' ) ) {
        $price_html  = '<span class="amount">' . wc_price( floatval( $unit_price ) ) . ' ' . __( "inc GST per bottle", "woocommerce") . '</span><br>';
        $price_html .= '<span class="amount">' . wc_price( floatval( $unit_price ) * 12 ) . ' ' . __( "inc GST per 12-bottles", "woocommerce") . '</span>';
    }
    return $price_html;
}



add_filter( 'woocommerce_cart_item_price', 'displayed_cart_item_unit_price', 10, 3 );
function displayed_cart_item_unit_price( $price, $cart_item, $cart_item_key ) {
    if ( $unit_price = $cart_item['data']->get_meta( 'unit_price' ) ) {
        $price = wc_price( floatval( $unit_price ) ) . ' ' . __( "inc GST per bottle", "woocommerce");
    }
    return $price;
} 

代码位于您的活动子主题(或活动主题)的 function.php 文件中。它应该有效。

在此处输入图像描述

现在,如果 WooCommerce 产品有效价格(默认)基于 12 瓶,您应该替换以下行(在第一个函数中)

$price_html .= '<span class="amount">' . wc_price( floatval( $unit_price ) * 12 ) . ' ' . __( "inc GST per 12-bottles", "woocommerce") . '</span>';

通过这一行:

$price_html .= '<span class="amount">' . wc_price( wc_get_price_to_display( $product ) ) . ' ' . __( "inc GST per 12-bottles", "woocommerce") . '</span>';

推荐阅读