When building a custom Woocommerce theme, you may come across some things that are tricky to implement. To further complicate matters, some of the available documentation may be lacking. Woocommerce is built to be plug and play, and for the most part that’s true. However, occasionally you’ll find yourself trying something a bit out of the box that goes against the default Woocommerce way of doing things. On a recent project, I came across one of these situations.
I wanted to get the numerical value of the lowest variation price, in order to be able to manipulate it when certain variation options are selected. Specifically, I wanted to have the price read “Priced from $XX” until all of the product attributes are selected, then display the final price. The standard default Woocommerce function to get a product’s price is the following function:
However, the issues with this are twofold:
It shows the price as a range of prices rather than a single minimum price. By default, Woocommerce displays variable prices in the following format: $100 – $200. It doesn’t want to show the user a final price until all of the potential product options are selected.
It comes already formatted, and in a specific nested div structure.This div structure includes <sbi> tags and additional formatting. I’m assuming this is done so that you could easily style the different parts for the price range via CSS. However, doing so makes it tricky to manipulate this data.
Theoretically, you can try extracting the first price, rip out the formatting, etc. But if this structure ever changes, your application would break in the future. This structure actually did change in a recent Woocommerce update. I knew there must be a better way to get the price data, minus the extra formatting.
After doing some digging, I found two very useful functions:
$product->get_variation_price( 'min' ) $product->get_variation_price( 'max' )
These two functions return the minimum and maximum values respectively for a variation product price in a numerical format. Here, the
$product->get_variation_price( 'min' )
I hope this simple tip was helpful if you ever come across this requirement in one of your projects. Happy Coding!