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.
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' ) was just what I needed, allowing me to easily get this value without having to jump through a bunch of hoops. Once I had this, I could manipulate it as needed, and then display the new price (adding formatting back in as needed). In my case, this function was perfect for my goal of wanting to display, “Priced from $XXX” before a variation product’s price when first viewing the product.
I hope this simple tip was helpful if you ever come across this requirement in one of your projects.