* Structured data's handler and generator using JSON-LD format.
* When making changes to this file, please make sure to test the generated
* markup with Schema Markup Validator and Google Search Console.
* * https://validator.schema.org/
* * https://search.google.com/test/rich-results
* @package WooCommerce\Classes
use Automattic\WooCommerce\Enums\OrderStatus;
use Automattic\WooCommerce\Enums\ProductType;
use Automattic\WooCommerce\Enums\ProductStockStatus;
defined( 'ABSPATH' ) || exit;
class WC_Structured_Data {
* Stores the structured data.
* @var array $_data Array of structured data.
private $_data = array();
public function __construct() {
// Generate structured data.
add_action( 'woocommerce_before_main_content', array( $this, 'generate_website_data' ), 30 );
add_action( 'woocommerce_breadcrumb', array( $this, 'generate_breadcrumblist_data' ), 10 );
add_action( 'woocommerce_single_product_summary', array( $this, 'generate_product_data' ), 60 );
add_action( 'woocommerce_email_order_details', array( $this, 'generate_order_data' ), 20, 3 );
// Output structured data.
add_action( 'woocommerce_email_order_details', array( $this, 'output_email_structured_data' ), 30, 3 );
add_action( 'wp_footer', array( $this, 'output_structured_data' ), 10 );
* @param array $data Structured data.
* @param bool $reset Unset data (default: false).
public function set_data( $data, $reset = false ) {
if ( ! isset( $data['@type'] ) || ! preg_match( '|^[a-zA-Z]{1,20}$|', $data['@type'] ) ) {
if ( $reset && isset( $this->_data ) ) {
public function get_data() {
* Structures and returns data.
* List of types available by default for specific request:
* @param array $types Structured data types.
public function get_structured_data( $types ) {
// Put together the values of same type of structured data.
foreach ( $this->get_data() as $value ) {
$data[ strtolower( $value['@type'] ) ][] = $value;
// Wrap the multiple values of each type inside a graph... Then add context to each type.
foreach ( $data as $type => $value ) {
$data[ $type ] = count( $value ) > 1 ? array( '@graph' => $value ) : $value[0];
$data[ $type ] = apply_filters( 'woocommerce_structured_data_context', array( '@context' => 'https://schema.org/' ), $data, $type, $value ) + $data[ $type ];
// If requested types, pick them up... Finally change the associative array to an indexed one.
$data = $types ? array_values( array_intersect_key( $data, array_flip( $types ) ) ) : array_values( $data );
if ( ! empty( $data ) ) {
if ( 1 < count( $data ) ) {
$data = apply_filters( 'woocommerce_structured_data_context', array( '@context' => 'https://schema.org/' ), $data, '', '' ) + array( '@graph' => $data );
* Get data types for pages.
protected function get_data_type_for_page() {
$types[] = is_shop() || is_product_category() || is_product() ? 'product' : '';
$types[] = is_shop() && is_front_page() ? 'website' : '';
$types[] = is_product() ? 'review' : '';
$types[] = 'breadcrumblist';
return array_filter( apply_filters( 'woocommerce_structured_data_type_for_page', $types ) );
* Makes sure email structured data only outputs on non-plain text versions.
* @param WP_Order $order Order data.
* @param bool $sent_to_admin Send to admin (default: false).
* @param bool $plain_text Plain text email (default: false).
public function output_email_structured_data( $order, $sent_to_admin = false, $plain_text = false ) {
echo '<div style="display: none; font-size: 0; max-height: 0; line-height: 0; padding: 0; mso-hide: all;">';
$this->output_structured_data();
* Sanitizes, encodes and outputs structured data.
* Hooked into `wp_footer` action hook.
* Hooked into `woocommerce_email_order_details` action hook.
public function output_structured_data() {
$types = $this->get_data_type_for_page();
$data = $this->get_structured_data( $types );
echo '<script type="application/ld+json">' . wc_esc_json( wp_json_encode( $data ), true ) . '</script>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
|--------------------------------------------------------------------------
|--------------------------------------------------------------------------
| Methods for generating specific structured data types:
| The generated data is stored into `$this->_data`.
| See the methods above for handling `$this->_data`.
* Generates Product structured data.
* Hooked into `woocommerce_single_product_summary` action hook.
* @param WC_Product $product Product data (default: null).
public function generate_product_data( $product = null ) {
if ( ! is_object( $product ) ) {
if ( ! is_a( $product, 'WC_Product' ) ) {
$shop_name = get_bloginfo( 'name' );
$currency = get_woocommerce_currency();
$permalink = get_permalink( $product->get_id() );
$image = wp_get_attachment_url( $product->get_image_id() );
'@id' => $permalink . '#product', // Append '#product' to differentiate between this @id and the @id generated for the Breadcrumblist.
'name' => wp_kses_post( $product->get_name() ),
'description' => wp_strip_all_tags( do_shortcode( $product->get_short_description() ? $product->get_short_description() : $product->get_description() ) ),
$markup['image'] = $image;
// Declare SKU or fallback to ID.
if ( $product->get_sku() ) {
$markup['sku'] = $product->get_sku();
$markup['sku'] = $product->get_id();
// Prepare GTIN and load it if it's valid.
$gtin = $this->prepare_gtin( $product->get_global_unique_id() );
if ( $this->is_valid_gtin( $gtin ) ) {
if ( '' !== $product->get_price() ) {
// Assume prices will be valid until the end of next year, unless on sale and there is an end date.
$price_valid_until = gmdate( 'Y-12-31', time() + YEAR_IN_SECONDS );
if ( $product->is_type( ProductType::VARIABLE ) ) {
$lowest = $product->get_variation_price( 'min', false );
$highest = $product->get_variation_price( 'max', false );
if ( $lowest === $highest ) {
'priceSpecification' => array(
'@type' => 'UnitPriceSpecification',
'price' => wc_format_decimal( $lowest, wc_get_price_decimals() ),
'priceCurrency' => $currency,
'valueAddedTaxIncluded' => wc_prices_include_tax(),
'validThrough' => $price_valid_until,
'@type' => 'AggregateOffer',
'lowPrice' => wc_format_decimal( $lowest, wc_get_price_decimals() ),
'highPrice' => wc_format_decimal( $highest, wc_get_price_decimals() ),
'offerCount' => count( $product->get_children() ),
if ( $product->is_on_sale() ) {
$lowest_child_sale_price = $product->get_variation_sale_price( 'min', false );
foreach ( $product->get_variation_prices()['sale_price'] as $variation_id => $variation_price ) {
if ( $variation_price === $lowest_child_sale_price ) {
$date_on_sale_to = isset( $variation_id )
? wc_get_product( $variation_id )->get_date_on_sale_to()
$sale_price_valid_until = $date_on_sale_to
? gmdate( 'Y-m-d', $date_on_sale_to->getTimestamp() )
$markup_offer['priceSpecification'] = array(
'@type' => 'UnitPriceSpecification',
'priceType' => 'https://schema.org/SalePrice',
'price' => wc_format_decimal( $lowest_child_sale_price, wc_get_price_decimals() ),
'priceCurrency' => $currency,
'valueAddedTaxIncluded' => wc_prices_include_tax(),
'validThrough' => $sale_price_valid_until ?? $price_valid_until,
} elseif ( $product->is_type( ProductType::GROUPED ) ) {
$tax_display_mode = get_option( 'woocommerce_tax_display_shop' );
$children = array_filter( array_map( 'wc_get_product', $product->get_children() ), 'wc_products_array_filter_visible_grouped' );
$price_function = 'incl' === $tax_display_mode ? 'wc_get_price_including_tax' : 'wc_get_price_excluding_tax';
foreach ( $children as $child ) {
if ( '' !== $child->get_regular_price() ) {
$child_prices[] = $price_function( $child, array( 'price' => $child->get_regular_price() ) );
if ( '' !== $child->get_sale_price() ) {
$child_sale_prices[] = $price_function( $child, array( 'price' => $child->get_sale_price() ) );
if ( empty( $child_prices ) ) {
$min_price = min( $child_prices );
if ( empty( $child_sale_prices ) ) {
$min_sale_price = min( $child_sale_prices );
$unit_price_specification = array(
'@type' => 'UnitPriceSpecification',
'price' => wc_format_decimal( $min_price, wc_get_price_decimals() ),
'priceCurrency' => $currency,
'valueAddedTaxIncluded' => wc_prices_include_tax(),
'validThrough' => $price_valid_until,
if ( $product->is_on_sale() && $min_price !== $min_sale_price ) {
// `priceType` should only be specified in prices which are not the current offer.
// https://developers.google.com/search/docs/appearance/structured-data/merchant-listing#sale-pricing-example
$unit_price_specification['priceType'] = 'https://schema.org/ListPrice';
'priceSpecification' => array(
$unit_price_specification,
if ( $product->is_on_sale() && $min_price !== $min_sale_price ) {
if ( $product->get_date_on_sale_to() ) {
$sale_price_valid_until = gmdate( 'Y-m-d', $product->get_date_on_sale_to()->getTimestamp() );
// We add the sale price to the top of the array so it's the first offer.
// See https://github.com/woocommerce/woocommerce/issues/55043.
$markup_offer['priceSpecification'],
'@type' => 'UnitPriceSpecification',
'price' => wc_format_decimal( $min_sale_price, wc_get_price_decimals() ),
'priceCurrency' => $currency,
'valueAddedTaxIncluded' => wc_prices_include_tax(),
'validThrough' => $sale_price_valid_until ?? $price_valid_until,
$unit_price_specification = array(
'@type' => 'UnitPriceSpecification',
'price' => wc_format_decimal( $product->get_regular_price(), wc_get_price_decimals() ),
'priceCurrency' => $currency,
'valueAddedTaxIncluded' => wc_prices_include_tax(),
'validThrough' => $price_valid_until,
if ( $product->is_on_sale() ) {
// `priceType` should only be specified in prices which are not the current offer.
// https://developers.google.com/search/docs/appearance/structured-data/merchant-listing#sale-pricing-example
$unit_price_specification['priceType'] = 'https://schema.org/ListPrice';
'priceSpecification' => array(
$unit_price_specification,
if ( $product->is_on_sale() ) {
if ( $product->get_date_on_sale_to() ) {
$sale_price_valid_until = gmdate( 'Y-m-d', $product->get_date_on_sale_to()->getTimestamp() );
// We add the sale price to the top of the array so it's the first offer.
// See https://github.com/woocommerce/woocommerce/issues/55043.
$markup_offer['priceSpecification'],
'@type' => 'UnitPriceSpecification',
'price' => wc_format_decimal( $product->get_sale_price(), wc_get_price_decimals() ),
'priceCurrency' => $currency,
'valueAddedTaxIncluded' => wc_prices_include_tax(),
'validThrough' => $sale_price_valid_until ?? $price_valid_until,
if ( $product->is_in_stock() ) {
$stock_status_schema = ( ProductStockStatus::ON_BACKORDER === $product->get_stock_status() ) ? 'BackOrder' : 'InStock';
$stock_status_schema = 'OutOfStock';
'priceValidUntil' => $sale_price_valid_until ?? $price_valid_until,
'availability' => 'http://schema.org/' . $stock_status_schema,
'@type' => 'Organization',
( ! empty( $markup_offer['price'] ) ||
! empty( $markup_offer['lowPrice'] ) ||
! empty( $markup_offer['highPrice'] )
) && empty( $markup_offer['priceCurrency'] )
$markup_offer['priceCurrency'] = $currency;
$markup['offers'] = array( apply_filters( 'woocommerce_structured_data_product_offer', $markup_offer, $product ) );
if ( $product->get_rating_count() && wc_review_ratings_enabled() ) {
$markup['aggregateRating'] = array(
'@type' => 'AggregateRating',
'ratingValue' => $product->get_average_rating(),
'reviewCount' => $product->get_review_count(),
// Markup 5 most recent rating/review.
$comments = get_comments(
'post_id' => $product->get_id(),
'post_status' => 'publish',
'post_type' => 'product',
'meta_query' => array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
$markup['review'] = array();
foreach ( $comments as $comment ) {
$markup['review'][] = array(
'ratingValue' => get_comment_meta( $comment->comment_ID, 'rating', true ),
'name' => get_comment_author( $comment ),
'reviewBody' => get_comment_text( $comment ),
'datePublished' => get_comment_date( 'c', $comment ),
// Check we have required data.
if ( empty( $markup['aggregateRating'] ) && empty( $markup['offers'] ) && empty( $markup['review'] ) ) {
$this->set_data( apply_filters( 'woocommerce_structured_data_product', $markup, $product ) );
* Generates Review structured data.
* Hooked into `woocommerce_review_meta` action hook.
* @param WP_Comment $comment Comment data.
public function generate_review_data( $comment ) {
$markup['@type'] = 'Review';
$markup['@id'] = get_comment_link( $comment->comment_ID );
$markup['datePublished'] = get_comment_date( 'c', $comment->comment_ID );
$markup['description'] = get_comment_text( $comment->comment_ID );
$markup['itemReviewed'] = array(
'name' => get_the_title( $comment->comment_post_ID ),
// Skip replies unless they have a rating.
$rating = get_comment_meta( $comment->comment_ID, 'rating', true );
$markup['reviewRating'] = array(
'ratingValue' => $rating,