Search code examples
phpwordpresswoocommerceproduct

Display in Woocommerce the product price per gram


On single product pages I'm trying to display the product price per gram. So, price divided by weight.

I can echo the price without currency symbol:

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

I can also echo the weight without 'g':

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

I know how to create a simple calculation:

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

But unsure how to put it all together!


Solution

  • There are some mistakes in your code. Since WooCommerce 3 get_price_including_tax() method is deprecated and replaced by wc_get_price_including_tax() function. Also you need to use the non formatted price for the calculation.

    Try the following:

    <?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");
    }
    ?>
    

    It should work.