Skip to content

Instantly share code, notes, and snippets.

@basepack
Last active November 6, 2018 14:13
Show Gist options
  • Save basepack/09fdbdd569020e2a0ff1 to your computer and use it in GitHub Desktop.
Save basepack/09fdbdd569020e2a0ff1 to your computer and use it in GitHub Desktop.
WooCommerce : add custom fields to product variations v2.0
<?php
//Display Fields
add_action( 'woocommerce_product_after_variable_attributes', 'variable_fields', 10, 3 );
//JS to add fields for new variations
add_action( 'woocommerce_product_after_variable_attributes_js', 'variable_fields_js' );
//Save variation fields
add_action( 'woocommerce_save_product_variation', 'save_variable_fields', 10, 1 );
/**
* Create new fields for variations
*
*/
function variable_fields( $loop, $variation_data, $variation ) {
?>
<tr>
<td>
<?php
// Text Field
woocommerce_wp_text_input(
array(
'id' => '_text_field['.$loop.']',
'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)
)
);
?>
</td>
</tr>
<tr>
<td>
<?php
// Number Field
woocommerce_wp_text_input(
array(
'id' => '_number_field['.$loop.']',
'label' => __( 'My Number Field', 'woocommerce' ),
'desc_tip' => 'true',
'description' => __( 'Enter the custom number here.', 'woocommerce' ),
'value' => get_post_meta($variation->ID, '_number_field'], true),
'custom_attributes' => array(
'step' => 'any',
'min' => '0'
)
)
);
?>
</td>
</tr>
<tr>
<td>
<?php
// Textarea
woocommerce_wp_textarea_input(
array(
'id' => '_textarea['.$loop.']',
'label' => __( 'My Textarea', 'woocommerce' ),
'placeholder' => '',
'description' => __( 'Enter the custom value here.', 'woocommerce' ),
'value' => get_post_meta($variation->ID, '_textarea'], true)
)
);
?>
</td>
</tr>
<tr>
<td>
<?php
// Select
woocommerce_wp_select(
array(
'id' => '_select['.$loop.']',
'label' => __( 'My Select Field', 'woocommerce' ),
'description' => __( 'Choose a value.', 'woocommerce' ),
'value' => get_post_meta($variation->ID, '_select'], true),
'options' => array(
'one' => __( 'Option 1', 'woocommerce' ),
'two' => __( 'Option 2', 'woocommerce' ),
'three' => __( 'Option 3', 'woocommerce' )
)
)
);
?>
</td>
</tr>
<tr>
<td>
<?php
// Checkbox
woocommerce_wp_checkbox(
array(
'id' => '_checkbox['.$loop.']',
'label' => __('My Checkbox Field', 'woocommerce' ),
'description' => __( 'Check me!', 'woocommerce' ),
'value' => get_post_meta($variation->ID, '_checkbox'], true)
)
);
?>
</td>
</tr>
<tr>
<td>
<?php
// Hidden field
woocommerce_wp_hidden_input(
array(
'id' => '_hidden_field['.$loop.']',
'value' => 'hidden_value'
)
);
?>
</td>
</tr>
<?php
}
/**
* Create new fields for new variations
*
*/
function variable_fields_js() {
?>
<tr>
<td>
<?php
// Text Field
woocommerce_wp_text_input(
array(
'id' => '_text_field[ + loop + ]',
'label' => __( 'My Text Field', 'woocommerce' ),
'placeholder' => 'http://',
'desc_tip' => 'true',
'description' => __( 'Enter the custom value here.', 'woocommerce' ),
'value' => ''
)
);
?>
</td>
</tr>
<tr>
<td>
<?php
// Number Field
woocommerce_wp_text_input(
array(
'id' => '_number_field[ + loop + ]',
'label' => __( 'My Number Field', 'woocommerce' ),
'desc_tip' => 'true',
'description' => __( 'Enter the custom number here.', 'woocommerce' ),
'value' => '',
'custom_attributes' => array(
'step' => 'any',
'min' => '0'
)
)
);
?>
</td>
</tr>
<tr>
<td>
<?php
// Textarea
woocommerce_wp_textarea_input(
array(
'id' => '_textarea[ + loop + ]',
'label' => __( 'My Textarea', 'woocommerce' ),
'placeholder' => '',
'description' => __( 'Enter the custom value here.', 'woocommerce' ),
'value' => '',
)
);
?>
</td>
</tr>
<tr>
<td>
<?php
// Select
woocommerce_wp_select(
array(
'id' => '_select[ + loop + ]',
'label' => __( 'My Select Field', 'woocommerce' ),
'description' => __( 'Choose a value.', 'woocommerce' ),
'value' => '',
'options' => array(
'one' => __( 'Option 1', 'woocommerce' ),
'two' => __( 'Option 2', 'woocommerce' ),
'three' => __( 'Option 3', 'woocommerce' )
)
)
);
?>
</td>
</tr>
<tr>
<td>
<?php
// Checkbox
woocommerce_wp_checkbox(
array(
'id' => '_checkbox[ + loop + ]',
'label' => __('My Checkbox Field', 'woocommerce' ),
'description' => __( 'Check me!', 'woocommerce' ),
'value' => '',
)
);
?>
</td>
</tr>
<tr>
<td>
<?php
// Hidden field
woocommerce_wp_hidden_input(
array(
'id' => '_hidden_field[ + loop + ]',
'value' => 'hidden_value'
)
);
?>
</td>
</tr>
<?php
}
/**
* Save new fields for variations
*
*/
function save_variable_fields( $post_id ) {
if (isset( $_POST['variable_sku'] ) ) :
$variable_sku = $_POST['variable_sku'];
$variable_post_id = $_POST['variable_post_id'];
// Text Field
$_text_field = $_POST['_text_field'];
for ( $i = 0; $i < sizeof( $variable_sku ); $i++ ) :
$variation_id = (int) $variable_post_id[$i];
if ( isset( $_text_field[$i] ) ) {
update_post_meta( $variation_id, '_text_field', stripslashes( $_text_field[$i] ) );
}
endfor;
// Number Field
$_number_field = $_POST['_number_field'];
for ( $i = 0; $i < sizeof( $variable_sku ); $i++ ) :
$variation_id = (int) $variable_post_id[$i];
if ( isset( $_text_field[$i] ) ) {
update_post_meta( $variation_id, '_number_field', stripslashes( $_number_field[$i] ) );
}
endfor;
// Textarea
$_textarea = $_POST['_textarea'];
for ( $i = 0; $i < sizeof( $variable_sku ); $i++ ) :
$variation_id = (int) $variable_post_id[$i];
if ( isset( $_textarea[$i] ) ) {
update_post_meta( $variation_id, '_textarea', stripslashes( $_textarea[$i] ) );
}
endfor;
// Select
$_select = $_POST['_select'];
for ( $i = 0; $i < sizeof( $variable_sku ); $i++ ) :
$variation_id = (int) $variable_post_id[$i];
if ( isset( $_select[$i] ) ) {
update_post_meta( $variation_id, '_select', stripslashes( $_select[$i] ) );
}
endfor;
// Checkbox
$_checkbox = $_POST['_checkbox'];
for ( $i = 0; $i < sizeof( $variable_sku ); $i++ ) :
$variation_id = (int) $variable_post_id[$i];
if ( isset( $_checkbox[$i] ) ) {
update_post_meta( $variation_id, '_checkbox', stripslashes( $_checkbox[$i] ) );
}
endfor;
// Hidden field
$_hidden_field = $_POST['_hidden_field'];
for ( $i = 0; $i < sizeof( $variable_sku ); $i++ ) :
$variation_id = (int) $variable_post_id[$i];
if ( isset( $_hidden_field[$i] ) ) {
update_post_meta( $variation_id, '_hidden_field', stripslashes( $_hidden_field[$i] ) );
}
endfor;
endif;
}
@optimuswebsites
Copy link

Hi, thanks for this code.
I get an error message:
Parse error: syntax error, unexpected ']'

Could you review this code?

@whoaloic
Copy link

whoaloic commented May 6, 2015

Hi,
thank you !
Do you know how to display variation value in the frontend?
I mean I'd like to show/hide the custom field data per the respective product variation selected by the user (like SKU or price).

@roltex
Copy link

roltex commented Dec 4, 2016

hi,
plz help! how i can to display it on front end?

@Reboon
Copy link

Reboon commented Dec 10, 2016

Hello, Remi

Could you usnswer us please! As roltex I have the same question to you: How can I show this field on the product page, for ex. put EAN field near SKU field. As I understand I need to open my theme woocommerce folder/single-product/meta.php and put here a code, something like sku code
I just starting to meet wordpress backend, could you please help me with this?
Thank you for your attention to this matter
Best regards, Sergey

@richardblondet
Copy link

Hello there,

just noticed there are brackets ] in the lines 27, 43, 63, 78, 98, in the second parameter of the function get_post_meta correspondingly, making the code break. Found them all by searching '],

Thanks for sharing!

Bests,
Richard

@jeesus
Copy link

jeesus commented May 8, 2017

WooCommerce 3 just came out. The function responsible for saving the data should be changed to something like this:

function save_custom_wc_fields( $variation_id, $i) {
	if (isset( $_POST["variable_sku"] ) ) {		
		$_text_field = isset($_POST["_my-super-duper-field"]) ? $_POST["_my-super-duper-field"] : false;
        if ($_text_field) {
            update_post_meta( $variation_id, "_rehvi-moot", stripslashes( $_text_field[$i] ) );
        }
    }
}

@colibriinteractive
Copy link

@roltex @whoaloic
I use

get_post_meta($variation_id, '_class_duration', true);

to display it in the frontend, where _class_duration is the name of my variable. As I saved just a number I want it to be returned not as an array but the value which is why I use the true.
See https://developer.wordpress.org/reference/functions/get_post_meta/ for further details.

Full code looks like this:

$all_orders = get_posts( array(
'numberposts' => -1,
'meta_key' => '_customer_user',
'meta_value' => get_current_user_id(),
'post_type' => wc_get_order_types(),
'post_status' => array_keys( wc_get_order_statuses() ),
) );

foreach($all_orders as $order){
$order_id = $order->ID;
$order = wc_get_order($order_id);

foreach ($order->get_items() as $item_id => $item_obj) {
	$variation_id = $item_obj->get_variation_id();
	$months = get_post_meta($variation_id, _class_duration, true);
	echo $months;
}

}

(Sorry, seems like the code is not correctly recognised as one by syntax highlighting. Not sure why)

Hope it helps anyway.
Best
Felix

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment