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



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

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

最新更新