How to add product image and description in product structured data (Schema.org) in WooCommerce

Viewed 461

I am using this to add a custom field to each product's schema

add_filter( 'woocommerce_structured_data_product', function( $markup, $product ) {
    if( is_product() ) {
        $markup['brand'] = get_post_meta(get_the_ID(), 'brand', TRUE);
    }

I also need to add the product's image url and description to the schema, how can I achieve this?

1 Answers

The woocommerce_structured_data_product hook already runs on the product page so you don't need the is_product() check.

As reported in the documentation, it is executed inside the woocommerce_single_product_summary hook.

You can override structured data like this:

// overwrites structured data
add_filter( 'woocommerce_structured_data_product',  'set_structured_data', 99, 2 );
function set_structured_data( $markup, $product ) {    
    $markup['brand'] = get_post_meta( $product->get_id(), 'brand', true );
    $markup['image'] = wp_get_attachment_url( $product->get_image_id() );
    $markup['description'] = wp_strip_all_tags( $product->get_short_description() ? $product->get_short_description() : $product->get_description() );
    return $markup;
}

The code has been tested and works. Add it to your active theme's functions.php.

On the product page, find the <script type="application/ld+json"> element, it should look something like this:

enter image description here

Then check if the brand, image and description fields are valued.

You can find a full list of fields to add to product structured data here:

If you want to check the validity of the structured data you can enter the entire script in the Code section of the Rich Results Test - Google Search Console page (instead of the product page url).

Some useful links:

Related answer:

Related