Search code examples
phpwordpresswoocommerceproduct

Make calculations on Woocommerce product price html and display it


In Woocommerce, I have this PHP code that output a product price and its fine.

But I need he too also print the price divided by 10. I tried many ways and it just doesn't work.

Heres the code:

    if ($hide_price !== '0') :
        $output_price .= '<div class="dhvc-woo-price dhvc-woo-span6">';
        $output_price .= $product->get_price_html (); //this is where the price is called
        $output_price .= '<p><br>Em até 10x de</p>'; //this is where it should print the price / by 10
        $output_price .= '</div>';
    endif;
    $output .= apply_filters('dhvc_woo_price', $output_price, $product, $display);

I tried $output_price .= $product->get_price_html() / 10; //it gives me 0

Also tried other ways and it just gave me php error.

Any help is appreciated.


Solution

  • You need to use wc_get_price_to_display($product) instead of $product->get_price_html() that will output the raw numerical price.

    The wc_get_price_to_display($product) will care about displayed with tax or not general option(which is not the case for $product->get_price()).

    The code:

    if ($hide_price !== '0') :
         $output_price .= '<div class="dhvc-woo-price dhvc-woo-span6">';
         $output_price .= $product->get_price_html (); //this is where the price is called
    
         // Here your correct price divided by 10 and formatted for the output
         $price_d10 = wc_price(wc_get_price_to_display($product) / 10);
         $output_price .= '<p><br>Em até 10x de '. $price_d10 .'</p>';
         $output_price .= '</div>';
     endif;
    
     $output .= apply_filters('dhvc_woo_price', $output_price, $product, $display);
    

    Tested and works