在 WooCommerce 产品上显示带有每米价格的自定义前缀

Display custom prefix with price per meter on WooCommerce products

我正在使用此代码在我的产品价格下方添加文字

function cw_change_product_price_display( $price ) {
    $price .= ' <span class="unidad">por unidad</span>';
    return $price;
}
add_filter( 'woocommerce_get_price_html', 'cw_change_product_price_display' );
add_filter( 'woocommerce_cart_item_price', 'cw_change_product_price_display' );

但我需要显示以下文本:每米的价格是:以及这个公式:

$product->get_price()/$product->get_length() . get_woocommerce_currency_symbol();

产品价格除以产品长度,无法在不导致站点错误的情况下正常工作。

另外,有什么方法可以使此代码仅适用于某些产品吗?因为有很多单位销售

您可以通过这种方式将其用于您的简单产品:

add_filter( 'woocommerce_get_price_html', 'custom_product_price_display', 10, 2 );
add_filter( 'woocommerce_cart_item_price', 'custom_product_price_display', 10, 2 );
function custom_product_price_display( $price, $product ) {
    if( ! is_a( $product, 'WC_Product' ) ) {
        $product = $product['data'];
    }
    
    // Price per meter prefixed
    if( $product->is_type('simple') && $product->get_length() ) {
        $unit_price_html = wc_price( $product->get_price() / $product->get_length() );
        $price .= ' <span class="per-meter">' . __("Price per meter is: ") . $unit_price_html . '</span>';
    } 
    return $price;
}

代码进入您的活动子主题(或活动主题)的 functions.php 文件。已测试并有效。


要同时处理“每米显示价格”和前缀“每单位”,请改用以下内容:

add_filter( 'woocommerce_get_price_html', 'custom_product_price_display', 10, 2 );
add_filter( 'woocommerce_cart_item_price', 'custom_product_price_display', 10, 2 );
function custom_product_price_display( $price, $product ) {
    if( ! is_a( $product, 'WC_Product' ) ) {
        $product = $product['data'];
    }
    
    // Price per meter prefixed
    if( $product->is_type('simple') && $product->get_length() ) {
        $unit_price_html = wc_price( $product->get_price() / $product->get_length() );
        $price .= ' <span class="per-meter">' . __("Price per meter is: ") . $unit_price_html . '</span>';
    } 
    // Prefix" per unit"
    else {
        $price .= ' <span class="per-unit">' . __("per unit") . $unit_price_html . '</span>';
    }
    return $price;
}