Wordpress - radio button checkout woocommerce show/hide required field - wordpress

I'm Italian (sorry for my english) and I'm not a programmer.
I need to insert in my checkout woocommerce site, a radio button with two options to answer this question: "Sei un privato cittadino, un'azienda o un libero professionista?".
These are the options:
1) Privato cittadino
2) Azienda o libero professionista
When users click on the first option, it has to show a required field: "codice fiscale". When users click on the second option, it has to show two required fields: "P.Iva" and "Ragione sociale". I've created the radio field with this code in form-billing.php:
<div class="woocommerce-billing-fields">
<?php if ( wc_ship_to_billing_address_only() && WC()->cart->needs_shipping() ) : ?>
<h3><?php _e( 'Billing & Shipping', 'woocommerce' ); ?></h3>
<?php else : ?>
<h3><?php _e( 'Billing Details', 'woocommerce' ); ?></h3>
<?
if($key=='billing_first_name')
{
?>
<p>Sei un privato cittadino, un'azienda o un libero professionista?</p>
<input type="radio" name="choice" value="privato_cittadino">Privato cittadino
<input type="radio" name="choice" value="azienda_professionista">Azienda o libero professionista<br>
<?
}
?>
<?php endif; ?>
It works properly, but now I don't know how can I create the required fields like I described.
Can you help me step by step? Please, consider I'm not a programmer.

To answer the question, it will need to be done in 4 steps.
Add 4 custom fields to the woocommerce checkout page. The way you have done it is not best practice and should be done through use of actions/filters.
Validate the data when the request is made to the back-end, this is to make sure the user actually selected and entered what is required.
Save the data to the order as post meta so it can be accessed later.
Implement javascript toggle feature so that based on what the user selects for the first question, the related fields are then shown.
Adding custom fields to woocommerce checkout
You will need to find a suitable action for where you would like to add the fields. I would recommend using the action woocommerce_after_checkout_billing_form as it will display fields after all the personal/billing information.
if( !function_exists( 'custom_checkout_question_field' ) ) {
/**
* Add custom question field after the billing form fields
*
* #param Integer $order_id New order id
*/
function custom_checkout_question_field( $checkout ) {
echo "<div class='custom-question-field-wrapper custom-question-1'>";
echo sprintf( '<p>%s</p>', __( "Sei un privato cittadino, un'azienda o un libero professionista?" ) );
woocommerce_form_field( 'custom_question_field', array(
'type' => 'radio',
'required' => true,
'class' => array('custom-question-field', 'form-row-wide'),
'options' => array(
'privato_cittadino' => 'Privato cittadino',
'azienda_professionista' => 'Azienda o libero professionista',
),
), $checkout->get_value( 'custom_question_field' ) );
woocommerce_form_field( 'custom_question_text_codice_fiscale', array(
'type' => 'text',
'label' => 'Codice Fiscale',
'required' => true,
'class' => array('custom-question-codice-fiscale-field', 'form-row-wide'),
), $checkout->get_value( 'custom_question_text_codice_fiscale' ) );
woocommerce_form_field( 'custom_question_text_p_iva', array(
'type' => 'text',
'label' => 'P.Iva',
'required' => true,
'class' => array('custom-question-p-iva-field', 'form-row-wide'),
), $checkout->get_value( 'custom_question_text_p_iva' ) );
woocommerce_form_field( 'custom_question_text_ragione_sociale', array(
'type' => 'text',
'label' => 'Ragione sociale',
'required' => true,
'class' => array('custom-question-ragione-sociale-field', 'form-row-wide'),
), $checkout->get_value( 'custom_question_text_ragione_sociale' ) );
echo "</div>";
}
add_action( 'woocommerce_after_checkout_billing_form', 'custom_checkout_question_field' );
}
Javascript front-end toggle
You will need to add custom javascript in order to toggle the 3 additional fields depending on the question. I have created a php function which will output a html script tag with some javascript. This is then attached to the wp_footer action.
This is not recommended method and you should really separate it into a new file js and enqueue the file when needed.
See: https://codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scripts
if( !function_exists( 'custom_question_conditional_javascript' ) ) {
function custom_question_conditional_javascript() {
?>
<script type="text/javascript">
(function() {
// Check if jquery exists
if(!window.jQuery) {
return;
};
var $ = window.jQuery;
$(document).ready(function() {
var questionField = $('.custom-question-field'),
codiceFiscaleField = $('.custom-question-codice-fiscale-field'),
pIvaField = $('.custom-question-p-iva-field'),
ragioneSocialeField = $('.custom-question-ragione-sociale-field ');
// Check that all fields exist
if(
!questionField.length ||
!codiceFiscaleField.length ||
!pIvaField.length ||
!ragioneSocialeField.length
) {
return;
}
function toggleVisibleFields() {
var selectedAnswer = questionField.find('input:checked').val();
if(selectedAnswer === 'privato_cittadino') {
codiceFiscaleField.show();
pIvaField.hide();
ragioneSocialeField.hide();
} else if(selectedAnswer === 'azienda_professionista') {
codiceFiscaleField.hide();
pIvaField.show();
ragioneSocialeField.show();
} else {
codiceFiscaleField.hide();
pIvaField.hide();
ragioneSocialeField.hide();
}
}
$(document).on('change', 'input[name=custom_question_field]', toggleVisibleFields);
$(document).on('updated_checkout', toggleVisibleFields);
toggleVisibleFields();
});
})();
</script>
<?php
}
add_action( 'wp_footer', 'custom_question_conditional_javascript', 1000 );
}
Getting fields from submitted post request
You will need to get the data from php $_POST array and also sanitise it to prevent sql injection or other malicious code. I have created a helper function which will grab all the fields by keys provided in an array and sanitise them using wordpress sanitize_text_field helper function.
This helper can then be used when validating and also adding post meta.
if( !function_exists( 'custom_checkout_question_get_field_values' ) ) {
/**
* Get all form field values based on user submitted post data
*
* #return Array Key/value pair of field values based on $_POST data
*/
function custom_checkout_question_get_field_values() {
$fields = [
'custom_question_field' => '',
'custom_question_text_codice_fiscale' => '',
'custom_question_text_p_iva' => '',
'custom_question_text_ragione_sociale' => '',
];
foreach( $fields as $field_name => $value ) {
if( !empty( $_POST[ $field_name ] ) ) {
$fields[ $field_name ] = sanitize_text_field( $_POST[ $field_name ] );
} else {
unset( $fields[ $field_name ] );
}
}
return $fields;
}
}
Validating fields on the back-end
Validation is important because front-end cannot be trusted, it is very easy for users to modify required fields on the front-end. You can use Woocommerce woocommerce_checkout_process action in order to validate the fields and add error messages if it does not meet what is required.
if( !function_exists( 'custom_checkout_question_field_validate' ) ) {
/**
* Custom woocommerce field validation to prevent user for completing checkout
*
* #param Integer $order_id New order id
*/
function custom_checkout_question_field_validate() {
$field_values = custom_checkout_question_get_field_values();
if ( empty( $field_values['custom_question_field'] ) ) {
wc_add_notice( 'Please select an answer for the question.', 'error' );
}
if (
$field_values['custom_question_field'] === 'privato_cittadino' &&
empty( $field_values['custom_question_text_codice_fiscale'] )
) {
wc_add_notice( 'Please enter codice fiscale.', 'error' );
}
if (
$field_values['custom_question_field'] === 'azienda_professionista' &&
empty( $field_values['custom_question_text_p_iva'] )
) {
wc_add_notice( 'Please enter p iva.', 'error' );
}
if (
$field_values['custom_question_field'] === 'azienda_professionista' &&
empty( $field_values['custom_question_text_ragione_sociale'] )
) {
wc_add_notice( 'Please enter ragione sociale.', 'error' );
}
}
add_action( 'woocommerce_checkout_process', 'custom_checkout_question_field_validate' );
}
Saving custom post meta to the order
You can use the woocommerce woocommerce_checkout_update_order_meta action in order to save additional post meta to the order post type. Here we will use the helper function custom_checkout_question_get_field_values created above to get all fields from php $_POST array and also sanitize them before saving each one to the post meta.
if( !function_exists( 'custom_checkout_question_field_save' ) ) {
/**
* Update order post meta based on submitted form values
*
* #param Integer $order_id New order id
*/
function custom_checkout_question_field_save( $order_id ) {
$field_values = custom_checkout_question_get_field_values();
foreach( $field_values as $field_name => $value ) {
if( !empty( $field_values[ $field_name ] ) ) {
update_post_meta( $order_id, $field_name, $value );
}
}
}
add_action( 'woocommerce_checkout_update_order_meta', 'custom_checkout_question_field_save' );
}

Related

Create a custom field on WooCommerce checkout if product category equals x

so I'm looking to create/show a couple of custom fields on the checkout page of my WooCommerce page as long as a product with a certain category is in the cart. The values of these fields are only necessary for me to access in the order on the backend afterwards, and does not need to be added to the order e-mail confirmation to the customer.
Any pointers? If it helps things, I'm using ACF on my website.
Thanks in advance!
You need to do the following:
Detect if the existing products in cart is in your category
Add the fields on checkout if it matches your condition.
Validate and save the data
Display it on the backend.
This is already outlined on the docs, and you might want to read it:
https://woocommerce.com/document/tutorial-customising-checkout-fields-using-actions-and-filters/#adding-a-custom-special-field
Here is an example function to detect if the cart contains a certain product within a defined category
// functions.php
function cat_in_cart( $cat_slug ) {
$cat_in_cart = false;
$cart = WC()->cart->get_cart();
if ( !$cart ) {
return $cat_in_cart;
}
foreach( $cart as $cart_item_key => $cart_item ) {
if ( has_term( $cat_slug, 'product_cat', $cart_item['product_id'] )) {
$cat_in_cart = true;
break;
}
}
return $cat_in_cart;
}
To add a field on checkout (Link to docs):
// functions.php
/**
* Add the field to the checkout
*/
add_action( 'woocommerce_after_order_notes', 'my_custom_checkout_field' );
function my_custom_checkout_field( $checkout ) {
if ( cat_in_cart( 'your_category_slug' ) ) {
echo '<div id="my_custom_checkout_field"><h2>' . __('My Field') . '</h2>';
woocommerce_form_field( 'my_field_name', array(
'type' => 'text',
'class' => array('my-field-class form-row-wide'),
'label' => __('Fill in this field'),
'placeholder' => __('Enter something'),
), $checkout->get_value( 'my_field_name' ));
echo '</div>';
}
}
After that, save the field on checkout:
add_action('woocommerce_checkout_process', 'my_custom_checkout_field_process');
function my_custom_checkout_field_process() {
// Check if set, if its not set add an error.
if ( ! $_POST['my_field_name'] )
wc_add_notice( __( 'Please enter something into this new shiny field.' ), 'error' );
}
add_action( 'woocommerce_checkout_update_order_meta', 'my_custom_checkout_field_update_order_meta' );
function my_custom_checkout_field_update_order_meta( $order_id ) {
if ( ! empty( $_POST['my_field_name'] ) ) {
update_post_meta( $order_id, 'My Field', sanitize_text_field( $_POST['my_field_name'] ) );
}
}
Lastly, display it on the dashboard:
/**
* Display field value on the order edit page
*/
add_action( 'woocommerce_admin_order_data_after_billing_address', 'my_custom_checkout_field_display_admin_order_meta', 10, 1 );
function my_custom_checkout_field_display_admin_order_meta($order){
echo '<p><strong>'.__('My Field').':</strong> ' . get_post_meta( $order->id, 'My Field', true ) . '</p>';
}

custom field value isn't stored in variation_data object

i have following issue with woocommerce/dokan:
I created a custom field for product variation:
custom field in wordpress backend
It works fine, the values are storing and i can change the value at the backend. Therefor i added following lines of code into function.php of theme file:
function variation_settings_fields( $loop, $variation_data, $variation ) {
// Text Field
woocommerce_wp_text_input(
array(
'id' => '_text_field[' . $variation->ID . ']',
'label' => __( 'My Text Field', 'woocommerce' ),
'placeholder' => 'http://',
'desc_tip' => 'true',
'description' => __( 'Enter the custom value here.', 'woocommerce' ),
'value' => get_post_meta( $variation->ID, '_text_field', true )
)
);
}
/**
* Save new fields for variations
*
*/
function save_variation_settings_fields( $post_id ) {
// Text Field
$text_field = $_POST['_text_field'][ $post_id ];
if( ! empty( $text_field ) ) {
update_post_meta( $post_id, '_text_field', esc_attr( $text_field ) );
}
}
// Add New Variation Settings
add_filter( 'woocommerce_available_variation', 'load_variation_settings_fields' );
/**
* Add custom fields for variations
*
*/
function load_variation_settings_fields( $variations ) {
// duplicate the line for each field
$variations['text_field'] = get_post_meta( $variations[ 'variation_id' ], '_text_field', true );
return $variations;
}
So far, so good. I can set a value and the value can be saved over the backend.
Now i want to change the custom field for this product variation in dokan vendor dashboard. I duplicated html-product-variation.php file into child theme and added the new field:
dokan vendor dashboard product variation
with following code:
<div>
<p class="dokan-form-group">
<label><?php esc_html_e( 'Custom Textfield', 'dokan' ); ?></label>
<textarea class="dokan-form-control" name="_text_field[<?php echo esc_attr( $loop ); ?>]" rows="3" style="width:100%;"><?php echo isset( $variation_data['_text_field'] ) ? esc_textarea( $variation_data['_text_field'] ) : ''; ?></textarea>
</p>
</div>
The problem is, that the value, which i set in the backend isn't shown and if i inspect the variation_data object there is no key in the array which says "_text_field". How can i store/update variation_data object?
I hope it's understandable which issue i'm facing here and look forward to some help :)
Best wishes,
Florian

Woocommerce - Validation on cart page

I have a custom filed for specific shipping methods (see screenshot).
Is there a hook/action to validate this field before proceeding the checkout. When I set the field to required the validation will fire at the checkout page but I want it at the cart page.
Validation:
//Validate the custom selection field
add_action('woocommerce_checkout_process', 'carrier_company_checkout_validation');
function carrier_company_checkout_validation() {
Load settings and convert them in variables
extract( custom_field_settings() );
if( isset( $_POST[$field_id] ) && empty( $_POST[$field_id] ) )
wc_add_notice(
sprintf( __("Please select a %s as it is a required field.","woocommerce"),
'<strong>' . $label_name . '</strong>'
), "error" );
}
** UPDATE: **
like #LoicTheAztec mentioned here the complete code.
Everything is working fine. The custom input value from cart will be shown on checkout and saved in the DB after order confirmation. But I don't know where I have to put the validation on the cart page when the custom input is empty because everything on cart is on ajax.
// ##########################################
// Add custom fields to a specific selected shipping method
// ##########################################
// Custom function that handle your settings
function delivery_date_settings(){
return array(
'field_id' => 'delivery_date', // Field Id
'field_type' => 'text', // Field type
'field_label' => 'label text', // Leave empty value if the first option has a text (see below).
'label_name' => __("Lieferdatum","woocommerce"), // for validation and as meta key for orders
);
}
// Display the custom checkout field
add_action( 'woocommerce_after_shipping_rate', 'carrier_company_custom_select_field', 20, 2 );
function carrier_company_custom_select_field( $method, $index ) {
if( $method->id == 'flat_rate:2' || $method->id == 'free_shipping:1') {
extract( delivery_date_settings() ); // Load settings and convert them in variables
$chosen = WC()->session->get('chosen_shipping_methods'); // The chosen methods
$value = WC()->session->get($field_id);
$value = WC()->session->__isset($field_id) ? $value : WC()->checkout->get_value('_'.$field_id);
$options = array(); // Initializing
$chosen_method_id = WC()->session->chosen_shipping_methods[ $index ];
if($chosen_method_id == 'flat_rate:2' || $method->id == 'free_shipping:1' ){
echo '<div class="custom-date-field">';
woocommerce_form_field( $field_id, array(
'type' => $field_type,
'label' => $field_label, // Not required if the first option has a text.
'class' => array('form-row-wide datepicker ' . $field_id . '-' . $field_type ),
'required' => false,
), $value );
echo '</div>';
// Jquery: Enable the Datepicker
?>
<script language="javascript">
jQuery( function($){
$('.datepicker input').datepicker({
dateFormat: 'dd.mm.yy', // ISO formatting date
});
});
</script>
<?php
}
}
}
// jQuery code (client side) - Ajax sender
add_action( 'wp_footer', 'carrier_company_script_js' );
function carrier_company_script_js() {
// Only cart & checkout pages
if( is_cart() || ( is_checkout() && ! is_wc_endpoint_url() ) ):
// Load settings and convert them in variables
extract( lieferdatum_settings() );
$js_variable = is_cart() ? 'wc_cart_params' : 'wc_checkout_params';
// jQuery Ajax code
?>
<script type="text/javascript">
jQuery( function($){
if (typeof <?php echo $js_variable; ?> === 'undefined')
return false;
$(document.body).on( 'change', 'input#<?php echo $field_id; ?>', function(){
var value = $(this).val();
$.ajax({
type: 'POST',
url: <?php echo $js_variable; ?>.ajax_url,
data: {
'action': 'delivery_date',
'value': value
},
success: function (result) {
console.log(result); // Only for testing (to be removed)
}
});
});
});
</script>
<?php
endif;
}
// The Wordpress Ajax PHP receiver
add_action( 'wp_ajax_delivery_date', 'set_carrier_company_name' );
add_action( 'wp_ajax_nopriv_delivery_date', 'set_carrier_company_name' );
function set_carrier_company_name() {
if ( isset($_POST['value']) ){
// Load settings and convert them in variables
extract( delivery_date_settings() );
if( empty($_POST['value']) ) {
$value = 0;
$label = 'Empty';
} else {
$value = $label = esc_attr( $_POST['value'] );
}
// Update session variable
WC()->session->set( $field_id, $value );
// Send back the data to javascript (json encoded)
echo $label;
die();
}
}
// Save custom field as order meta data
add_action( 'woocommerce_checkout_create_order', 'save_carrier_company_as_order_meta', 30, 1 );
function save_carrier_company_as_order_meta( $order ) {
// Load settings and convert them in variables
extract( delivery_date_settings() );
if( isset( $_POST[$field_id] ) && ! empty( $_POST[$field_id] ) ) {
$order->update_meta_data( '_'.$field_id, esc_attr($_POST[$field_id]) );
WC()->session->__unset( $field_id ); // remove session variable
}
}
// Display custom field in admin order pages
add_action( 'woocommerce_admin_order_data_after_shipping_address', 'admin_order_display_carrier_company', 30, 1 );
function admin_order_display_carrier_company( $order ) {
// Load settings and convert them in variables
extract( delivery_date_settings() );
$carrier = $order->get_meta( '_'.$field_id ); // Get carrier company
if( ! empty($carrier) ) {
// Display
echo '<p><strong>' . $label_name . '</strong>: ' . $carrier . '</p>';
}
}
// Display carrier company after shipping line everywhere (orders and emails)
add_filter( 'woocommerce_get_order_item_totals', 'display_carrier_company_on_order_item_totals', 1000, 3 );
function display_carrier_company_on_order_item_totals( $total_rows, $order, $tax_display ){
// Load settings and convert them in variables
extract( delivery_date_settings() );
$carrier = $order->get_meta( '_'.$field_id ); // Get carrier company
if( ! empty($carrier) ) {
$new_total_rows = [];
// Loop through order total rows
foreach( $total_rows as $key => $values ) {
$new_total_rows[$key] = $values;
// Inserting the carrier company under shipping method
if( $key === 'shipping' ) {
$new_total_rows[$field_id] = array(
'label' => $label_name,
'value' => $carrier,
);
}
}
return $new_total_rows;
}
return $total_rows;
}
I think the hook you're looking for is woocommerce_check_cart_items, that's the one that validates the cart items before proceeding to checkout.
I'm not 100% sure whether you'll be able to get the field in the same way using $_POST but it's worth a go.

Add custom field as item meta data on the Order

I have added a custom field to the woocommerce products, it is working well with the following code. But my problem is how to add it to the cart_item_data
// Display Text in Admin Panel
add_action('woocommerce_product_options_general_product_data', 'product_custom_text_field');
function product_custom_text_field()
{
// Custom Product Text Field ( para Tex Area -> woocommerce_wp_textarea_input )
woocommerce_wp_text_input(
array(
'id' => '_optional_text_field',
'label' => __('Customize title', 'woocommerce'),
'placeholder' => '',
'desc_tip' => 'true',
'description' => __('Customizable title for the field that the user must fill out.', 'woocommerce')
)
);
}
Save Fields
add_action('woocommerce_process_product_meta', 'product_custom_text_field_save');
function product_custom_text_field_save($post_id)
{
if (!empty($_POST['_optional_text_field'])) {
update_post_meta($post_id, '_optional_text_field', esc_attr($_POST['_optional_text_field']));
}
}
Display The Text in Product Page
add_action('woocommerce_single_variation', 'display_text_field');
function display_text_field()
{
global $post;
if (get_post_meta($post->ID, '_optional_text_field', true)) {
echo "<div class='titulo-c'><label>";
echo get_post_meta($post->ID, '_optional_text_field', true);
echo "</label></div>";
return;
}
echo __('FREE LOCAL SHIPPING', 'woocommerce');
}
So far it works without problems, now I want to add it to the cart_item_data, with the following code, but it does not work for me.
add_filter( 'woocommerce_add_cart_item_data', 'add_cart_item_data', 25, 2 );
function add_cart_item_data( $cart_item_meta, $product_id ) {
$custom_data = array() ;
$custom_data[ "_optional_text_field"] = isset( $_POST['_optional_text_field'] ) ? sanitize_text_field ( $_POST['_optional_text_field'] ) : "" ;
$cart_item_meta ['custom_data'] = $custom_data ;
return $cart_item_meta;
}
Display custom data on cart and checkout page.
add_filter( 'woocommerce_get_item_data', 'get_item_data' , 25, 2 );
function get_item_data ( $other_data, $cart_item ) {
if ( isset( $cart_item [ 'custom_data' ] ) ) {
$custom_data = $cart_item [ 'custom_data' ];
$other_data[] = array( 'name' => 'Title',
'display' => $custom_data['_optional_text_field'] );
}
return $other_data;
}
As a result, it only appears to me: Title: ________
I will appreciate any suggestions to make my code work.
Make the following changes to your code as below, this should work.
/**
* Add data to cart item
*/
add_filter( 'woocommerce_add_cart_item_data', 'add_cart_item_data', 25, 2 );
function add_cart_item_data( $cart_item_meta, $product_id ) {
global $woocommerce;
$mytitle_form_data = get_post_meta($product_id, '_optional_text_field', true);
$custom_data = array() ;
$custom_data[ "_optional_text_field"] = $mytitle_form_data;
$cart_item_meta ['custom_data'] = $custom_data ;
return $cart_item_meta;
}

Display custom fields in variations product page WooCommerce

I've created two custom fields in variations with the following code (Thanks Remi Corso):
functions.php
Add Variation Settings
add_action( 'woocommerce_product_after_variable_attributes', 'variation_settings_fields', 10, 3 );
Save Variation Settings
add_action( 'woocommerce_save_product_variation', 'save_variation_settings_fields', 10, 2 );
Create new fields for variations
function variation_settings_fields( $loop, $variation_data, $variation ) {
woocommerce_wp_text_input(
array(
'id' => '_pdf_ficha_tecnica[' . $variation->ID . ']',
'label' => __( 'PDF FICHA TÉCNICA', 'woocommerce' ),
'placeholder' => 'http://',
'desc_tip' => 'true',
'description' => __( 'aqui', 'woocommerce' ),
'value' => get_post_meta( $variation->ID, '_pdf_ficha_tecnica', true )
)
);
woocommerce_wp_text_input(
array(
'id' => '_pdf_ficha_caracteristicas[' . $variation->ID . ']',
'label' => __( 'PDF FICHA CARACTERÍSTICAS', 'woocommerce' ),
'placeholder' => 'http://',
'desc_tip' => 'true',
'description' => __( 'aqui', 'woocommerce' ),
'value' => get_post_meta( $variation->ID, '_pdf_ficha_caracteristicas', true )
)
);
}
Save new fields for variations
function save_variation_settings_fields( $post_id ) {
$text_field = $_POST['_pdf_ficha_tecnica'][ $post_id ];
if( ! empty( $text_field ) ) {
update_post_meta( $post_id, '_pdf_ficha_tecnica', esc_attr( $text_field ) );
}
$text_field = $_POST['_pdf_ficha_caracteristicas'][ $post_id ];
if( ! empty( $text_field ) ) {
update_post_meta( $post_id, '_pdf_ficha_caracteristicas', esc_attr( $text_field ) );
}
}
These custom fields store URLs and will be displayed as links <a href>. I looking to display these fields but I'm having a lot of trouble finding the right solution.
Can anyone guide me?
Should I focus on file "variable.php"?
And the JS?
Or can I render the fields by hooks?
The following code I created works perfectly. I am new to JS and I'm sure can be improved. I hope that will be helpful. To create Custom Fields reads the post of REMI.
Explanation: With "WC_Product Variable" object can display the Custom Fields of product variation,
To display these fields I used jquery, the contents of the span "sku" will be our reference as shown on the product page. This code in the "variations.php" file.
<?php
// With "WC_Product Variable" object I get the Custom Fields variations.
$product_id = $product->id;
$variation = new WC_Product_Variable( $product_id );
$arrvariations = $variation->get_children ();
// With foreach construct the div that will contain the Custom Fields
foreach ($arrvariations as $varid) {
$cfvalone = get_post_meta( $varid, '_custom_field_one', true );
$cfvaltwo = get_post_meta( $varid, '_custom_field_two', true );
// Check the Custom Fields are not empty
if (!empty($cfvalone) or !empty($cfvaltwo) ) {
$cfonecont = get_post_meta( $varid, '_custom_field_one', true );
$cftwocont = get_post_meta( $varid, '_custom_field_two', true );
$varsku = get_post_meta( $varid, '_sku', true );
// Built the DIV and embed SKU of the variation to be processed later by JS.
?>
<div class="varskudiv" data-varskudiv="<? echo $varsku;?>" style="display:none;">
<?php if (!empty($cfonecont)) {?>
CUSTOM FIELD ONE
<?php } ?>
<?php if (!empty($cftwocont)) {?>
CUSTOM FIELD TWO
<?php } ?>
</div>
<? }}?>
<br/>
<script>
jQuery(document).ready(function( $ ) {
// As we will take the contents of SPAN "sku" to create the JS
//we must consider that this SPAN is complete once the screen is loaded.
$(window).bind("load", function() {
woosku = $(".sku").text();
// Now we map the DIV we created "varskudiv" and load those values in an ARRAY
wooarrsku = $('div.varskudiv').map(function(){
return $(this).data('varskudiv');
}).get();
// Now we make loop, if the values match show the DIV.
var indexsku;
for (indexsku = 0; indexsku < wooarrsku.length; indexsku++) {
if (woosku == wooarrsku[indexsku]) {
$('.varskudiv[data-varskudiv="'+ woosku +'"]').css( "display", "inline-block" );
}
}
});
// Once loaded the screen, if the SPAN "sku" changes, start the process again and hide the previous DIV displayed.
$('.sku').bind("DOMSubtreeModified",function(){
woosku = $(".sku").text();
wooarrsku = $('div.varskudiv').map(function(){
return $(this).data('varskudiv');
}).get();
var indexsku;
for (indexsku = 0; indexsku < wooarrsku.length; indexsku++) {
if (woosku == wooarrsku[indexsku]) {
$('.varskudiv[data-varskudiv="'+ woosku +'"]').css( "display", "inline-block" );
}
else {$('.varskudiv[data-varskudiv="'+ wooarrsku[indexsku] +'"]').css( "display", "none" );
}
}
});
});
</script>

Resources