在 Woocommerce 中显示每克产品价格

Display in Woocommerce the product price per gram

在单个产品页面上,我试图显示每克的产品价格。所以,价格除以重量。

我可以回显没有货币符号的价格:

<?php global $post; $product = new WC_Product($post->ID); echo wc_price($product->get_price_including_tax(1,$product->get_price())); ?>

不用'g'我也可以回显权重:

<?php global $product; $attributes = $product->get_attributes(); if ( $product->has_weight() ) { echo $product->get_weight();} ?>

我知道如何创建一个简单的计算:

<?php $first_number = 10; $second_number = 20; $sum_total = $second_number / $first_number; print ($sum_total); ?>

但不确定如何将它们组合在一起!

您的代码中有一些错误。由于 WooCommerce 3 get_price_including_tax() 方法已弃用并被 wc_get_price_including_tax() 函数取代。另外您需要使用非格式化价格进行计算。

尝试以下操作:

<?php 
global $product; 

if ( ! is_a( $product, 'WC_Product' ) ) {
    $product = wc_get_product( get_the_ID() );
}

$price  = wc_get_price_including_tax( $product );
$weight = $product->get_weight();

if( $product->has_weight() ) {
    // echo __("Weight") . ': ' . wc_format_weight( $weight ) . '<br>'; // Uncomment if needed
    echo wc_price( $price / $weight ) . ' ' . __("per gram");
}
?>

应该可以。