New Native Gtin Field In Woocommerce

Woocommerce has finally implemented the field for the GTIN code natively. How can I output this for simple and variations in the template?

Also looking for this. Have you found an answer Claudio?

Unfortunately, only single products are still rendered. I haven’t found a solution for the variations yet, but I haven’t looked any further because the customer changed his mind and didn’t want to display the gtin field in frontend.
I have created a future request for this and hope that bricks will then integrate this feature:

I used this:

// Shortcode voor GTIN, UPC, EAN of ISBN
function display_wc_product_gtin() {
global $product;

if (!$product instanceof WC_Product) {
    return '';
}

// Haal GTIN uit het veld _global_unique_id
$gtin = get_post_meta($product->get_id(), '_global_unique_id', true);

return !empty($gtin) ? esc_html($gtin) : '';

}
add_shortcode(‘wc_product_gtin’, ‘display_wc_product_gtin’);

Works good

1 Like

If you, like me, prefer the handlebars approach, this works by typing {product_gtin} or picking it from the list in the editor:

function product_gtin() {
	if ( ! function_exists( 'wc_get_product' ) ) {
		return '';
	}

	// Prefer current WooCommerce product if available.
	$product = wc_get_product();
	if ( $product instanceof WC_Product ) {
		$gtin = get_post_meta( $product->get_id(), '_global_unique_id', true );
		return $gtin ? esc_html( $gtin ) : '';
	}

	// Fallback to global $post if no WC product context.
	global $post;
	if ( $post instanceof WP_Post ) {
		$gtin = get_post_meta( $post->ID, '_global_unique_id', true );
		return $gtin ? esc_html( $gtin ) : '';
	}

	return '';
}

// Dynamic tag picker
add_filter( 'bricks/dynamic_tags_list', function( $tags ) {
	$tags[] = [
		'name'  => '{product_gtin}',
		'label' => 'Product GTIN',
		'group' => 'Post',
	];

	return $tags;
} );

// Tag renderer
add_filter( 'bricks/dynamic_data/render_tag', function( $tag, $post, $context ) {
	if ( ! is_string( $tag ) ) {
		return $tag;
	}
	return product_gtin();
}, 20, 3 );

function render_product_gtin_tag( $content, $post, $context = 'text' ) {
	if ( strpos( $content, '{product_gtin}' ) === false ) {
		return $content;
	}

	$value = product_gtin();

	return str_replace( '{product_gtin}', $value, $content );
}

add_filter( 'bricks/dynamic_data/render_content', 'render_product_gtin_tag', 20, 3 );
add_filter( 'bricks/frontend/render_data', 'render_product_gtin_tag', 20, 2 );
1 Like

Thanks. I use it and works perfectly.

1 Like