I have this code where I need to insert a value based on a condition in: **///////// HERE THE MY CODE /////////**
Here I have overridden single-product/add-to-cart/variation.php
Woocommerce template file via my active theme:
<script type="text/template" id="tmpl-variation-template">
<div class="woocommerce-variation-description">
{{{ data.variation.variation_description }}}
</div>
<div class="woocommerce-variation-price">
{{{ data.variation.price_html }}}
</div>
<div class="woocommerce-variation-custom_field">
{{{ data.variation.custom_field}}}
///////// HERE MY CODE /////////
</div>
<div class="woocommerce-variation-availability">
{{{ data.variation.availability_html }}}
</div>
</script>
The condition should check the value of the variable `{{{ data.variation.custom_field}}}` and if this data is greater than 10 then the code should print "Yes".
**Something like**:
if( $data.variation.custom_field > 10 ){
echo "yes";
}
But it's not working. I guess, this should be done using Javascript instead of php but I don't know how grab the variable value.
2
Answers
Based on https://codex.wordpress.org/Javascript_Reference/wp.template and similar template engine like https://github.com/blueimp/JavaScript-Templates#evaluation, you need to build a template with evaluation.
In your case, it should be something like:
Also, here https://lkwdwrd.com/wp-template-js-templates-wp you can find an example with if statement itself.
There is no need to use additional javascript (or jQuery) code for that.
The following will handle a product variation custom field displaying "YES" if the custom field value is bigger than 10 (otherwise nothing).
You will need to replace your exiting hooked function that use
woocommerce_available_variation
hook, with one of the following ways.There are mainly 2 ways:
1). The simplest way, without overriding
variation.php
template:Code goes in functions.php file of the active child theme (or active theme). Tested and works.
2). Another simple way (overriding
variation.php
template):Code goes in functions.php file of the active child theme (or active theme).
Then in your custom template
single-product/add-to-cart/variation.php
you will replace:with:
It will work nicely without any additional requirements.
Here is a complete code example for the community, based on the 2nd Way:
1). Admin variations: Display a custom field and save it’s value
Code goes in functions.php file of the active child theme (or active theme).
2). Frontend variations: Conditional display based on selected variation and custom field value
Code goes in functions.php file of the active child theme (or active theme).
3). Template override:
single-product/add-to-cart/variation.php
file to your active theme’s:Tested and works.
Related: WooCommerce: Add/display Product or Variation custom field everywhere