Search code examples
phpwordpresswoocommerceproduct

Outputting the product html price increased of 20%


In WooCommerce, I am trying to output the product html price increased of 20% using this code:

echo $product->get_price_html(); // +20%

I have tried for a long time to get it working but unfortunately I cannot do so.
How can I achieve that?


Solution

  • First you have to know that the variable $product is an instance of WC_Product class, that will allow you to apply to it any methods from this WC_Product class.

    You can use WC_Product method get_price() and WC_Product method adjust_price() this way:

    // Get the numerical (float) price value
    $product_price = (float) $product->get_price();
    
    // calculate 20% of product price
    $add_to_price = $product_price * 0.2;
    
    // Adjust the new displayed price
    $product->adjust_price( $add_to_price );
    
    // Displaying the new adjusted price html
    echo $product->get_price_htm();
    

    So now you finally get the html product price output increased of 20% simply reusing WC_Product get_price_html() method