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

时间:2020-07-26 19:18:55

标签: php wordpress woocommerce product price

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

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();

产品价格除以产品长度,如果不引起网站错误就无法正常工作。

还有,有什么方法可以使此代码仅适用于某些产品?由于每单位售出的商品很多

1 个答案:

答案 0 :(得分:2)

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

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