On my Woocommerce category pages, I want to grab the existing query results and use it to populate the schema data for OfferCatalog.
This is the closest function I can find to what I need:
/**
* Add structured data to the WooCommerce shop page.
*
* @param array $markup The structured data markup.
* @param WP_Query $query The current WP_Query object.
* @return array The modified structured data markup.
*/
function add_structured_data_to_shop_page( $markup, $query ) {
if ( is_shop() || is_product_category() || is_product_tag() ) {
$markup['@type'] = 'CollectionPage';
$markup['mainEntity']['@type'] = 'OfferCatalog';
$markup['mainEntity']['itemListElement'] = array();
$products = $query->get_posts();
foreach ( $products as $product ) {
$markup['mainEntity']['itemListElement'][] = array(
'@type' => 'Product',
'name' => get_the_title( $product->ID ),
'url' => get_permalink( $product->ID ),
'image' => get_the_post_thumbnail_url( $product->ID, 'full' ),
'description' => get_the_excerpt( $product->ID ),
'offers' => array(
'@type' => 'Offer',
'price' => get_post_meta( $product->ID, '_price', true ),
'priceCurrency' => get_woocommerce_currency(),
'availability' => 'https://schema.org/InStock', // Adjust as needed
),
);
}
}
return $markup;
}
add_filter( 'woocommerce_structured_data', 'add_structured_data_to_shop_page', 10, 2 );
But nothing is output. I suspect the woocommerce_structured_data
has been disabled or removed from the category pages. I’ve tried different hooks, but still see nothing output.
How can I make this work (without repeating the database query)?