phpwordpresswoocommerceschemaproduct

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?


Solution

  • 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).