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

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


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


慕森王
浏览 112回答 1
1回答

倚天杖

您可以将其用于简单的产品: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 ) {&nbsp; &nbsp; if( ! is_a( $product, 'WC_Product' ) ) {&nbsp; &nbsp; &nbsp; &nbsp; $product = $product['data'];&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; // Price per meter prefixed&nbsp; &nbsp; if( $product->is_type('simple') && $product->get_length() ) {&nbsp; &nbsp; &nbsp; &nbsp; $unit_price_html = wc_price( $product->get_price() / $product->get_length() );&nbsp; &nbsp; &nbsp; &nbsp; $price .= ' <span class="per-meter">' . __("Price per meter is: ") . $unit_price_html . '</span>';&nbsp; &nbsp; }&nbsp;&nbsp; &nbsp; 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 ) {&nbsp; &nbsp; if( ! is_a( $product, 'WC_Product' ) ) {&nbsp; &nbsp; &nbsp; &nbsp; $product = $product['data'];&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; // Price per meter prefixed&nbsp; &nbsp; if( $product->is_type('simple') && $product->get_length() ) {&nbsp; &nbsp; &nbsp; &nbsp; $unit_price_html = wc_price( $product->get_price() / $product->get_length() );&nbsp; &nbsp; &nbsp; &nbsp; $price .= ' <span class="per-meter">' . __("Price per meter is: ") . $unit_price_html . '</span>';&nbsp; &nbsp; }&nbsp;&nbsp; &nbsp; // Prefix" per unit"&nbsp; &nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp; $price .= ' <span class="per-unit">' . __("per unit") . $unit_price_html . '</span>';&nbsp; &nbsp; }&nbsp; &nbsp; return $price;}
打开App,查看更多内容
随时随地看视频慕课网APP