I added the custom fields to product variations (following this guide. It's work fine but it add the custom fields to all products. I would like to add the custom fields only to specific products and its variations. For example: if product id is equal to '1234' then WP add custom fields to its variations.
I try to work on this in function.php:
global $post;
$product_id = $post->ID;
$product_array = array( 1234, 9999 );
if ( in_array( $product_id, $product_array )) {
// add custom field
}
...but it works only on the product and not on its variations.
It's possibile? Thank you very much!
To target specific variable products (and all its variations), you can directly get the parent variable product ID from the
$variations3rd function argument (the WP_Post object of the current variation), usingpost_parentfield.So you will use instead:
Here is a complete code example with an input text field:
Code goes in functions.php file of your child theme (or in a plugin). Tested and works.
For multiple input text fields:
You can use the following optimized code version (where the fields settings are in a reusable custom function):
Then to add this custom-fields to the variable product form data, use: