Function: Get Variants Prices Based on 2d Attributes Values

In the past weeks I’ve had the opportunity to work on several projects including modifying the design of a WooCommerce variable product.

While I could have probably completed all projects using WordPress hooks & actions, since some of them also needed some JS and CSS functionality, Iv’e decided to seek a different approach.

For one of the projects, I needed to to create an array that given 2 attributes values (which would be the method to identify the variation) would return the variation’s price.

On the backend, this is possible using some of WooCommerce functions such as $product->get_available_variations,  $product->get_attributes(), and wc_get_product_terms() – perhaps in future posts I will demonstrate how.

On the frontend though, there isn’t an easy access to these function. However, interestingly enough, WooCommerce prints a JSON encoded version of $product->get_available_variations() into their form element, data-product_variations attribute.

Since I couldn’t find online a WooCommerce global variable which JSON decodes this data, Iv’e done it by myself in the first lines of the attached code.

Assuming our variable product has 2 attributes (which the attached function does), then by inputting 2 attribute values – the function would return the variant price.

Here is the function:

Let me know if it helped you, and if you have any suggestions for improving this function.

p.s. I wonder what would be the performance implications for a large data set.


Published by

Yaniv Friedensohn

I am a Codeable developer (only top 3% of developers are accepted) specializing in creating advanced WordPress and WooCommerce solutions for clients worldwide. Projects include developing a custom shopping workflow and adding functionality to existing plugins. You can contact me at [email protected]