phpwordpresswoocommerceschemayoast

WooCommerce: Add brand and gtin to product schema markup in Yoast


I want to add a brand and a gtin to my product markup in WooCommerce. At the moment the Yoast SEO plugin already adds a lot of markup. But it only has the option to add the brand with a product attribute. In my case the brand is based on a custom field. Also the gtin is in a different field and couldn't be used with Yoast.

I found a code snippet in their docs which allows to add custom data to the markup:

add_filter( 'wpseo_schema_webpage', 'example_change_webpage' );

/**
 * Changes @type of Webpage Schema data.
 *
 * @param array $data Schema.org Webpage data array.
 *
 * @return array Schema.org Webpage data array.
 */
function example_change_webpage( $data ) {
    if ( ! is_page( 'about' ) ) {
        return $data;
    }

    $data['@type'] = 'AboutPage';

    return $data;
}

But that's not for products and I couldn't see how I can change that.

I also found an example for the schmea piece product:

{
      "@context": "https://schema.org",
      "@graph": [
          {
              "@type": "Product",
              "@id": "https://www.example.com/#/schema/product/abc123",
              "name": "Example Product",
              "image": {
                  "@id": "https://www.example.com/#/schema/image/abc123"
              }
          }
      ]
  }

I could use that in a custom function and add it as javascript in the head. Like this:

add_action( 'wp_head', function() {

    if ( is_product() ): 
    
    ?>
    
    <script type="application/ld+json">{
          "@context": "https://schema.org",
          "@graph": [
              {
                  "@type": "Product",
                  "@id": "#product",
                  "brand": {
                      "@id": "https://www.example.com/#/schema/organization/abc123"
                  },
                  "sku": "abc123",
              }
          ]
      }</script>
    
<?php
endif;
 }, 99 );

But now I have two different schema markups for the product.

Isn't there a way to add content to the existing markup from Yoast?


Solution

  • The above-approved answer won't work unless you are using Yoast SEO woocommerce plugin. You can use the code below to add brand and gtin.

    add_filter( 'woocommerce_structured_data_product', 'custom_set_extra_schema', 20, 2 );
    function custom_set_extra_schema( $schema, $product ) {
    
        $gtin       = get_post_meta( $product->get_id(), '_custom_gtin', true );
        $brand_name = get_post_meta( $product->get_id(), '_custom_brand_name', true );
    
        $schema['brand']  = $brand_name;
        $schema['gtin13'] = $gtin;
    
        return $schema;
    }