Adding JSON Structured Data to WordPress

If you’re creating the theme yourself, you can always use Schema Microata markup directly in the theme itself.

As we can see in the below example, adding extra attributes to your HTML can make it Schema compliant. In this instance, we are using itemscope, itemtype and itemprop:

Taken from http://schema.org/docs/gs.html#microdata_how

<div itemscope itemtype ="http://schema.org/Movie">
  <h1 itemprop="name">Avatar</h1>
  <div itemprop="director" itemscope itemtype="http://schema.org/Person">
  Director: <span itemprop="name">James Cameron</span> (born <span itemprop="birthDate">August 16, 1954</span>)
  </div>
  <span itemprop="genre">Science fiction</span>
  <a href="https://wordpress.stackexchange.com/questions/240234/movies/avatar-theatrical-trailer.html" itemprop="trailer">Trailer</a>
</div>

However if you want to use JSON-LD markup, then you might want to consider generating the JSON-LD using a PHP JSON-LD library and injecting the code into your header by attaching it to the wp_head function:

Mashed together from the PHP-JSON-LD GitHub example:

<?php

// Describe your Thing to be marked up as an array
$doc = (object) array(
    "http://schema.org/name" => "Manu Sporny",
    "http://schema.org/url" => (object) array("@id" => "http://manu.sporny.org/"),
    "http://schema.org/image" => (object) array("@id" => "http://manu.sporny.org/images/manu.png")
);

// Describe it's schema context as well
$context = (object)array(
  "name" => "http://schema.org/name",
  "homepage" => (object)array("@id" => "http://schema.org/url", "@type" => "@id"),
  "image" => (object)array("@id" => "http://schema.org/image", "@type" => "@id")
);

function wp_json_ld($doc, $context) {
    require_once('/path/to/library');

    // Pass it through this magical function
    $compacted = jsonld_compact($doc, $context);

    echo '<script type="application/ld+json">';
    echo json_encode($compacted, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
    echo '</script>';
}

/* Output:
<script type="application/ld+json">
{
  "@context": {...},
  "image": "http://manu.sporny.org/images/manu.png",
  "homepage": "http://manu.sporny.org/",
  "name": "Manu Sporny"
}
</script>
*/

// Add it to wp_head
add_action('wp_head', 'wp_json_ld');