Search code examples
phpwordpresswoocommercejson-ldgoogle-rich-snippets

How do I include WordPress PHP tags in JSON-LD?


I want to add JSON-LD structured data to my WordPress WooCommerce site in order to increase my chances of rich snippets on search engine results pages.

I want to begin by adding it first to my products pages.

If I've included the code below in header-shop.php...

    <!-- Include Schema Markup File
–––––––––––––––––––––––––––––––––––––––––––––––––– -->
<?php include('json-ld.php'); ?><script type="application/ld+json"><?php echo json_encode($payload); ?></script>

how do I reference PHP tags like <php the_title(); ?> within the json-ld.php file?

Is it as simple as the following?

<script type="application/ld+json">
{
  "@context": "http://schema.org/",
  "@type": "Product",
  "name": "<?php the_title(); ?>",
  "image": [
    "https://example.com/photos/1x1/photo.jpg",
    "https://example.com/photos/4x3/photo.jpg",
    "https://example.com/photos/16x9/photo.jpg"
   ],
  "brand": {
    "@type": "Thing",
    "name": "ACME"
  },
  "aggregateRating": {
    "@type": "AggregateRating",
    "ratingValue": "4.4",
    "ratingCount": "89"
  },
  "offers": {
    "@type": "AggregateOffer",
    "lowPrice": "119.99",
    "highPrice": "199.99",
    "priceCurrency": "USD"
  }
}
</script>

Solution

  • You could do this in PHP to print to your page. By echoing your script in entirety will allow you to concat inline functions.

    echo '
    <script type="application/ld+json">
    {
      "@context": "http://schema.org/",
      "@type": "Product",
      "name": "'. the_title() .'",
      "image": [
        "https://example.com/photos/1x1/photo.jpg",
        "https://example.com/photos/4x3/photo.jpg",
        "https://example.com/photos/16x9/photo.jpg"
       ],
      "brand": {
        "@type": "Thing",
        "name": "ACME"
      },
      "aggregateRating": {
        "@type": "AggregateRating",
        "ratingValue": "4.4",
        "ratingCount": "89"
      },
      "offers": {
        "@type": "AggregateOffer",
        "lowPrice": "119.99",
        "highPrice": "199.99",
        "priceCurrency": "USD"
      }
    }
    </script>
    ';