Php 商品价格后缀,根据商品中的重量计算价格

Php 商品价格后缀,根据商品中的重量计算价格,php,wordpress,woocommerce,product,price,Php,Wordpress,Woocommerce,Product,Price,我正在使用“https://stackoverflow.com/questions/53435276/custom-product-price-suffix-on-based-on-product-categories-in-woocommerce/53438506#53438506“回答允许通过以下方式使用前缀调整我的定价显示的线程: $price .= ' ' . __('/ $7.50 per serving'); 但实际上我想让$price输出物品的价格除以物品的重量。我该怎么

我正在使用“https://stackoverflow.com/questions/53435276/custom-product-price-suffix-on-based-on-product-categories-in-woocommerce/53438506#53438506“回答允许通过以下方式使用前缀调整我的定价显示的线程:

    $price .= ' ' . __('/ $7.50 per serving');
但实际上我想让
$price
输出物品的价格除以物品的重量。我该怎么做

以下是我的实际代码稍加修改(使用
has\u product\u categories()
from):


我尝试了一大堆在前端输出
NAN
的东西。别以为我做得对

以下内容将添加您的前缀和每种服务的计算价格:

add_filter( 'woocommerce_get_price_html', 'conditional_price_suffix', 10, 2 );
function conditional_price_suffix( $price, $product ) {
    $weight    = (float) $product->get_weight();
    $raw_price = (float) wc_get_price_to_display($product);

    // Handling product variations
    $product_id = $product->is_type('variation') ? $product->get_parent_id() : $product->get_id();

    // HERE define your product categories (can be IDs, slugs or names)
    $product_categories = array('monthly-menus');
    $product_categories = array('clothing');

    if( has_product_categories( $product_categories, $product_id ) && $weight > 0 )
        $price .= ' ' . sprintf( __('/ %s per serving'), strip_tags( wc_price( $weight / $raw_price ) ) );
    return $price;
}
您必须包括来自的功能代码

代码进入活动子主题(或活动主题)的function.php文件。测试和工作

add_filter( 'woocommerce_get_price_html', 'conditional_price_suffix', 10, 2 );
function conditional_price_suffix( $price, $product ) {
    $weight    = (float) $product->get_weight();
    $raw_price = (float) wc_get_price_to_display($product);

    // Handling product variations
    $product_id = $product->is_type('variation') ? $product->get_parent_id() : $product->get_id();

    // HERE define your product categories (can be IDs, slugs or names)
    $product_categories = array('monthly-menus');
    $product_categories = array('clothing');

    if( has_product_categories( $product_categories, $product_id ) && $weight > 0 )
        $price .= ' ' . sprintf( __('/ %s per serving'), strip_tags( wc_price( $weight / $raw_price ) ) );
    return $price;
}