By default WooCommerce adds structured data for every single published product in JSON format. It is a great feature which not only helps the search engines to crawl important information about a product but it also helps with the overall SEO (Search Engine Optimization) strategy of an WooCommerce based eCommerce site.
It is important to note that by default WooCommerce does not add all the properties recommended by Google or even Schema.org. For an example, you can think of the Brand name or GTIN number of a product which are not available within the default structured data generated by WooCommerce. This is where our role comes into place to fill-in the gap and add the additional data. On this post, today I will show how to add custom structured data from WooCommerce. Here is the sample code snippet.
// sample snippet for adding custom structured data
add_filter('woocommerce_structured_data_product','custom_structured_data', 10, 2);
function custom_structured_data($markup, $product) {
if (empty($markup['key'])) {
$markup['key'] = 'value';
}
return $markup;
}
Explanation
Little explanation is necessary before you start using this snippet. On the snippet above I am using the woocommerce filter hook in order to inject or insert our custom structured data in "key" & "value" pair format using a custom function. Now, all you need to do is to define the key the and the value as you desire. List of all the keys can be found from the Schema.org webpage link I mentioned above. I will show another example below for better understanding.
Adding Product Meta Data
You can add any product meta data within the structured data block. On one of my previous post, I already discussed on how to add the custom GTIN meta field for simple WooCommerce product and save it as product meta data on our database table. For the sake of simplicity, I will use that data here as an example. This is how it works.
add_filter('woocommerce_structured_data_product','add_product_gtin_number', 10, 2);
function add_product_gtin_number($markup, $product) {
if (empty($markup['gtin8'])) {
$markup['gtin8'] = get_post_meta($product->get_id(),'_gtin', true);
}
return $markup;
}
As you can see from this snippet, I changed the "key" with "gtin8". As per Google & Schema.org, Valid GTIN related keys are (gtin8, gtin13, gtin14), you can use whatever you need. I am using get_post_meta function to retrieve the GTIN value of the product using "_gtin" meta key. You can use different meta key instead of "_gtin" to retrieve any product meta data. All you need to do is simply change the meta key here and place this snippet on your current theme's function.php page. Hope that helps.
Comments