user15346394
user15346394

Reputation:

Customize WooCommerce product structured data schema ean / identifier_exists

I am using this snippet to display ean value for gtin in Woocommerce's product schema:

add_filter( 'woocommerce_structured_data_product', 'filter_woocommerce_structured_data_product', 10, 2 ); 

function filter_woocommerce_structured_data_product( $markup, $product ) { 
if ( empty( $markup[ 'gtin8' ] ) ) {
    $markup[ 'gtin8' ] = get_post_meta( $product->get_id(), 'ean', true );
}

return $markup;
}

This works but I need to set "identifier_exists" markup to products that don't have the custom field ean set. How can I modify my snippet to show the ean value in the markup if it exists, and add the identifier_exists attribute = false to products that don't have an ean?

Upvotes: 3

Views: 1885

Answers (2)

Vincenzo Di Gaetano
Vincenzo Di Gaetano

Reputation: 4110

The gtin field must be set based on its length.
Here you will find the complete documentation with all available fields.

The gtin must be of type text (not numeric).

Finally, the gtin field is optional. If your product does not have the EAN code (or any other identifier) you can simply not set the gtin.

Even if you set the identifier_exists field to no or false you will still see the "No global identifier provided (e.g., gtin, mpn, isbn) (optional)" warning. You can just ignore it. In fact, it is not reported in the documentation.

You can do some tests here: https://search.google.com/test/rich-results

// set the gtin in the structured data of the product
add_filter( 'woocommerce_structured_data_product', 'custom_schema', 99, 2 );
function custom_schema( $markup, $product ) {
    // get the product identifier
    $ean = get_post_meta( $product->get_id(), 'ean', true );
    // set gtin based on length
    switch ( strlen($ean) ) {
        case 8:
            $markup['gtin8'] = (string)$ean;
            break;
        case 12:
            $markup['gtin12'] = (string)$ean;
            break;
        case 13:
            $markup['gtin13'] = (string)$ean;
            break;
        case 14:
            $markup['gtin14'] = (string)$ean;
            break;
        default:
            $markup['identifier_exists'] = 'no';
            break;
    }
    return $markup;
}

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

Related answer:

Upvotes: -1

LoicTheAztec
LoicTheAztec

Reputation: 254212

Try the following:

add_filter( 'woocommerce_structured_data_product', 'custom_schema', 99, 2 );
function custom_schema( $markup, $product ) {
    $value = $product->get_meta( 'ean' );
    $length = strlen($value);

    if ( ! empty($value) ) {
        $markup['identifier_exists'] = true;
        $markup['gtin'.$length]      = $value;
    } else {
        $markup['identifier_exists'] = false;
    }
    return $markup;
}

Code goes in functions.php file of the active child theme (or active theme).

Upvotes: 0

Related Questions