Add GTIN/EAN/UPC to WooCommerce products with PHP

/**
 * Adds "GTIN" admin input field to the "Product data" meta box > "Inventory" tab.
 *
 * @see https://wpcodebook.com/snippets/add-gtin-ean-upc-to-woocommerce-products-with-php/
 * @see https://github.com/woocommerce/woocommerce/blob/7.9.0/plugins/woocommerce/includes/admin/meta-boxes/views/html-product-data-inventory.php#L32
 * @see https://github.com/woocommerce/woocommerce/blob/7.9.0/plugins/woocommerce/includes/admin/wc-meta-box-functions.php#L23
 */
add_action( 'woocommerce_product_options_sku', function () {
	global $product_object;
	woocommerce_wp_text_input(
		array(
			'id'    => 'gtin',
			'value' => $product_object->get_meta( 'gtin', true, 'edit' ),
			'label' => __( 'GTIN' ),
		)
	);
} );

/**
 * Saves "GTIN" admin input field in product meta.
 *
 * @see https://wpcodebook.com/snippets/add-gtin-ean-upc-to-woocommerce-products-with-php/
 * @see https://github.com/woocommerce/woocommerce/blob/7.9.0/plugins/woocommerce/includes/admin/meta-boxes/class-wc-meta-box-product-data.php#L422
 */
add_action( 'woocommerce_admin_process_product_object', function ( $product ) {
	if ( isset( $_POST['gtin'] ) ) {
		$product->update_meta_data( 'gtin', wc_clean( wp_unslash( $_POST['gtin'] ) ) );
	}
} );

/**
 * Displays GTIN in the product's meta section on the frontend.
 *
 * @see https://wpcodebook.com/snippets/add-gtin-ean-upc-to-woocommerce-products-with-php/
 * @see https://github.com/woocommerce/woocommerce/blob/7.9.0/plugins/woocommerce/templates/single-product/meta.php#L26
 */
add_action( 'woocommerce_product_meta_start', function () {
	global $product;
	if ( $gtin = $product->get_meta( 'gtin' ) ) {
		printf( '<span class="gtin">%s: %s</span>', esc_html__( 'GTIN' ), $gtin );
	}
} );

/**
 * Adds GTIN to product structured data.
 *
 * @see https://wpcodebook.com/snippets/add-gtin-ean-upc-to-woocommerce-products-with-php/
 * @see https://github.com/woocommerce/woocommerce/blob/7.9.0/plugins/woocommerce/includes/class-wc-structured-data.php#L334
 */
add_filter( 'woocommerce_structured_data_product', function ( $markup, $product ) {
	if ( '' !== ( $gtin = $product->get_meta( 'gtin' ) ) ) {
		$markup['gtin'] = $gtin;
	}
	return $markup;
}, 10, 2 );

Leave a Comment