'Getting the product price of a WooCommerce product with Timber, Twig and ACF outside of WooCommerce
I'm building a custom product loop outside of WooCommerce and I have setup a repeater loop within ACF where they can select the product they want to display and it returns the product's object; however this doesn't quite seem to match the same object you would get back with using the WC function get_product, as in, the price details are returned like this:
[_regular_price] => 14.99
[_sale_price] =>
[_price] => 14.99
These fields aren't accessible like many other fields as they start with an underscore.
The above data comes from a loop, such as:
{% for product in post.get_field('showcase_products') %}
...
{% endfor %}
I also tried doing product.get_price in Twig but it doesn't work.
I was then able to try doing the below:
{% set price = fn('wc_get_product', product.id) %}
Then I was able to use any of the below:
{{ fn('print_r', price.price) }}
{{ fn('print_r', price.get_price) }}
{{ fn('print_r', price.get_price_html) }}
Is there a way to be able to get the above data without the extra call to the WC function wc_get_product within each loop?
Solution 1:[1]
however this doesn't quite seem to match the same object you would get back with using the WC function get_product
This is because the ACF repeater field is set to return WP_Post data in an array, even for the "product" post type. ACF doesn't convert each post in the repeater array to a Woocommerce product for you, so you have to do it manually on each loop as you have {% set price = fn('wc_get_product', product.id) %}
Even Timber uses the wc_get_product function in their docs here https://timber.github.io/docs/guides/woocommerce/
I don't think there's anything particularly wrong or resource heavy in converting each post in the array with that function.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Web Assembler |
