2

I need to show a list of simple and variable products with their prices displayed as "From $XX". But I've seen some methods like below.

$min_price  = $product->get_variation_price( 'min', true ); //I guess this only works for variable products
$min_price = $product->get_price_html(); //Will this guarantee to show the priceof the cheapest variation in a variable product?
$min_price = $product->get_price(); //How about this?

So, which is the best way to ensure I always get the lowest price for products regardless of them being simple or variable.

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
worisi24
  • 129
  • 3
  • 11

1 Answers1

3

The minimum price is exclusively for variable products (price range)

For variable products only to get the min active price amount (non formatted) you will use:

$min_price = $product->get_variation_price( 'min' );
$min_price_for display = $product->get_variation_price( 'min', true ); // for display

For other product types (including variations) to get the active price amount (non formatted) you will use:

$price = $product->get_price();

For all products to get the formatted displayed price, you will use:

$formatted_price = $product->get_price_html(); 

This last one can give a price range for variable products and for products on sale.


Related: WooCommerce variable products: keep only "min" price with a custom label

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
  • You're the man! I've learned so much from all your answers on StackOverflow. But may I ask, what do you mean by ACTIVE price under "$price = $product->get_price();" Do you mean the price that are enabled/visible/set in each variation or simple product or a price of one product that has been actively purchased (like most people purchase a product variation at a specific price) – worisi24 Aug 15 '19 at 10:04
  • @worisi24 If product is on sale, the active price is the sale price, if not it is the regular price *(because you can also use the `WC_Product` methods `get_sale_price()` or `get_regular_price()`)*. – LoicTheAztec Aug 15 '19 at 10:23