Skip to content

Instantly share code, notes, and snippets.

@Yogeshkad
Forked from tankbar/functions.php
Created May 12, 2021 18:24
Show Gist options
  • Save Yogeshkad/fd98b0e7f76c016092543798731758db to your computer and use it in GitHub Desktop.
Save Yogeshkad/fd98b0e7f76c016092543798731758db to your computer and use it in GitHub Desktop.
WooCommerce - Add GTIN/EAN meta field for product and product variations
/**
* Adding Custom GTIN Meta Field
* Save meta data to DB
*/
// add GTIN input field
add_action('woocommerce_product_options_inventory_product_data','woocom_simple_product_gtin_field', 10, 1 );
function woocom_simple_product_gtin_field(){
global $woocommerce, $post;
$product = new WC_Product(get_the_ID());
echo '<div id="gtin_attr" class="options_group">';
//add GTIN field for simple product
woocommerce_wp_text_input(
array(
'id' => '_gtin',
'label' => __( 'GTIN', 'textdomain' ),
'placeholder' => '01234567891231',
'desc_tip' => 'true',
'description' => __( 'Enter the Global Trade Item Number (UPC,EAN,ISBN)', 'textdomain' )
)
);
echo '</div>';
}
// save simple product GTIN
add_action('woocommerce_process_product_meta','woocom_simple_product_gtin_save');
function woocom_simple_product_gtin_save($post_id){
$gtin_post = $_POST['_gtin'];
// save the gtin
if(isset($gtin_post)){
update_post_meta($post_id,'_gtin', esc_attr($gtin_post));
}
// remove if GTIN meta is empty
$gtin_data = get_post_meta($post_id,'_gtin', true);
if (empty($gtin_data)){
delete_post_meta($post_id,'_gtin', '');
}
}
// Add Variation GTIN Meta Field
add_action( 'woocommerce_product_after_variable_attributes', 'variation_settings_fields', 10, 3 );
function variation_settings_fields( $loop, $variation_data, $variation ) {
// Text Field
woocommerce_wp_text_input(
array(
'id' => '_gtin[' . $variation->ID . ']',
'label' => __( 'GTIN', 'textdomain' ),
'placeholder' => '01234567891231',
'desc_tip' => 'true',
'description' => __( 'Enter the Global Trade Item Number (UPC,EAN,ISBN)', 'textdomain' ),
'value' => get_post_meta( $variation->ID, '_gtin', true )
)
);
}
// Save Variation GTIN Meta Field Settings
add_action( 'woocommerce_save_product_variation', 'save_variation_settings_fields', 10, 2 );
function save_variation_settings_fields( $post_id ) {
$gtin_post = $_POST['_gtin'][ $post_id ];
// save the gtin
if(isset($gtin_post)){
update_post_meta($post_id,'_gtin', esc_attr($gtin_post));
}
// remove if GTIN meta is empty
$gtin_data = get_post_meta($post_id,'_gtin', true);
if (empty($gtin_data)){
delete_post_meta($post_id,'_gtin', '');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment