Skip to content

Instantly share code, notes, and snippets.

@daliborgogic
Created April 14, 2020 07:09
Show Gist options
  • Save daliborgogic/bef206dcb2b92f8e4e04d2de4a0a0fd0 to your computer and use it in GitHub Desktop.
Save daliborgogic/bef206dcb2b92f8e4e04d2de4a0a0fd0 to your computer and use it in GitHub Desktop.
Global Trade Identification Number (GTIN) WooCommerce
<?php
/**
* Global Trade Identification Numbers (GTINs) to WooCommerce products.
* Render the Global Trade Identification Number (GTIN) meta field.
*/
function woocommerce_render_gtin_field() {
$input = array(
'id' => '_gtin',
'label' => sprintf(
'<abbr title="%1$s">%2$s</abbr>',
_x( 'Global Trade Identification Number', 'field label', 'my-theme' ),
_x( 'GTIN', 'abbreviated field label', 'my-theme' )
),
'value' => get_post_meta( get_the_ID(), '_gtin', true ),
'desc_tip' => true,
'description' => __( 'Enter the Global Trade Identification Number (UPC, EAN, ISBN, etc.)', 'my-theme' ),
);
?>
<div id="gtin_attr" class="options_group">
<?php woocommerce_wp_text_input( $input ); ?>
</div>
<?php }
add_action( 'woocommerce_product_options_inventory_product_data', 'woocommerce_render_gtin_field' );
/**
* Save the product's GTIN number, if provided.
*
* @param int $product_id The ID of the product being saved.
*/
function woocommerce_save_gtin_field($product_id) {
if (
! isset( $_POST['_gtin'], $_POST['woocommerce_meta_nonce'] )
|| ( defined( 'DOING_AJAX' ) && DOING_AJAX )
|| ! current_user_can( 'edit_products' )
|| ! wp_verify_nonce( $_POST['woocommerce_meta_nonce'], 'woocommerce_save_data' )
) {
return;
}
$gtin = sanitize_text_field( $_POST['_gtin'] );
update_post_meta( $product_id, '_gtin', $gtin );
}
add_action( 'woocommerce_process_product_meta','woocommerce_save_gtin_field' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment