Schema Markup For WooCommerce Product

Here’s an example code snippet for adding dynamic product schema markup to WooCommerce products:

add_action( 'wp_head', 'add_product_schema_markup' );

function add_product_schema_markup() {
    if ( is_product() ) {
        global $product;
        $product_id = $product->get_id();
        $product_name = $product->get_name();
        $product_description = $product->get_description();
        $product_price = $product->get_price();
        $product_currency = get_woocommerce_currency();
        $product_availability = $product->is_in_stock() ? 'InStock' : 'OutOfStock';
        $product_image_id = $product->get_image_id();
        $product_image_url = wp_get_attachment_image_src( $product_image_id, 'full' )[0];

        $schema_markup = '
            <script type="application/ld+json">
            {
              "@context": "https://schema.org/",
              "@type": "Product",
              "name": "' . esc_html( $product_name ) . '",
              "description": "' . esc_html( $product_description ) . '",
              "sku": "' . esc_html( $product_id ) . '",
              "image": "' . esc_url( $product_image_url ) . '",
              "brand": {
                "@type": "Thing",
                "name": "Your Brand Name Here"
              },
              "offers": {
                "@type": "Offer",
                "priceCurrency": "' . esc_html( $product_currency ) . '",
                "price": "' . esc_html( $product_price ) . '",
                "availability": "' . esc_html( $product_availability ) . '"
              }
            }
            </script>
        ';

        echo $schema_markup;
    }
}

This code uses the wp_head action hook to add product schema markup to the head section of the page if the current page is a single product page (is_product() returns true). The code first gets the product ID, name, description, price, currency, availability, and image URL using various WooCommerce product methods. Then it uses these values to generate a JSON-LD script tag containing the product schema markup.

Note that you may need to modify this code to fit your specific needs, such as changing the brand name or adding more product properties to the schema markup. Also, make sure to test the schema markup using Google’s Structured Data Testing Tool or another schema markup testing tool to ensure that it is valid and properly formatted.

Leave comment or code correction