add_action('wp_head', 'eo_product_schema', 99);
function eo_product_schema() {
if ( ! is_product() ) {
return;
}
global $product;
if ( ! $product || ! is_a( $product, 'WC_Product' ) ) {
$product = wc_get_product( get_the_ID() );
}
if ( ! $product ) {
return;
}
$schema = array(
'@context' => 'https://schema.org',
'@type' => 'Product',
'@id' => get_permalink( $product->get_id() ) . '#product',
'name' => html_entity_decode( $product->get_name(), ENT_QUOTES ),
'url' => get_permalink( $product->get_id() ),
);
// Description
$description = wp_strip_all_tags( $product->get_description() );
if ( ! empty( $description ) ) {
$schema['description'] = $description;
}
// Image
$image = wp_get_attachment_url( $product->get_image_id() );
if ( $image ) {
$schema['image'] = array( esc_url( $image ) );
}
// SKU
if ( $product->get_sku() ) {
$schema['sku'] = $product->get_sku();
}
// Brand
$schema['brand'] = array(
'@type' => 'Brand',
'name' => 'Executive Optical'
);
// Ratings
$rating = (float) $product->get_average_rating();
$reviews = (int) $product->get_review_count();
if ( $reviews > 0 && $rating > 0 ) {
$schema['aggregateRating'] = array(
'@type' => 'AggregateRating',
'ratingValue' => $rating,
'reviewCount' => $reviews,
'bestRating' => 5,
'worstRating' => 1
);
}
// Offer
if ( $product->get_price() !== '' ) {
$schema['offers'] = array(
'@type' => 'Offer',
'url' => get_permalink( $product->get_id() ),
'priceCurrency' => get_woocommerce_currency(),
'price' => (string) wc_format_decimal( $product->get_price(), 2 ),
'availability' => $product->is_in_stock()
? 'https://schema.org/InStock'
: 'https://schema.org/OutOfStock',
'itemCondition' => 'https://schema.org/NewCondition'
);
}
echo '';
}
Skip to content