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.
The Situation
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:
$product->get_price_html()
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.
The Solution
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. And if you're ever in need of WooCommerce development solutions, don't hesitate to reach out to Curious Minds. Our experienced team can provide a wide range of services, from headless CMS development and professional SEO optimization to enterprise WordPress development solutions. Contact us today to learn more and take your web presence to the next level.
Happy Coding!