Add JSON-LD structured data to WordPress posts and pages with PHP

JSON-LD structured data for WordPress posts with PHP

Structured data tells search engines what a page is: an article with an author and a date, a position in a breadcrumb trail, an organisation. Google reads it best as JSON-LD, a <script type="application/ld+json"> block in the page. A theme can generate it from data WordPress already has, without a plugin.

Problem: Posts have no structured data, so search results show no article details, and an SEO plugin for this one feature is not wanted.

Solution: On wp_head, build PHP arrays for the BlogPosting of the current post and its BreadcrumbList, encode them with wp_json_encode() and print them in one application/ld+json script. Check the result with Google’s Rich Results Test.

The article

add_action( 'wp_head', 'ha_json_ld', 20 );

function ha_json_ld() {
    if ( ! is_singular( 'post' ) ) {
        return;
    }
    $post  = get_queried_object();
    $graph = [];

    $article = [
        '@type'            => 'BlogPosting',
        '@id'              => get_permalink( $post ) . '#article',
        'headline'         => wp_strip_all_tags( get_the_title( $post ) ),
        'datePublished'    => get_post_time( 'c', true, $post ),
        'dateModified'     => get_post_modified_time( 'c', true, $post ),
        'mainEntityOfPage' => get_permalink( $post ),
        'author'           => [
            '@type' => 'Person',
            'name'  => get_the_author_meta( 'display_name', $post->post_author ),
            'url'   => get_author_posts_url( $post->post_author ),
        ],
        'publisher'        => [
            '@type' => 'Organization',
            'name'  => get_bloginfo( 'name' ),
            'logo'  => [ '@type' => 'ImageObject', 'url' => get_site_icon_url( 512 ) ],
        ],
    ];
    $image = get_the_post_thumbnail_url( $post, 'full' );
    if ( $image ) {
        $article['image'] = $image;
    }
    $graph[] = $article;
    $graph[] = ha_breadcrumb_schema( $post );

    echo '<script type="application/ld+json">'
        . wp_json_encode( [ '@context' => 'https://schema.org', '@graph' => $graph ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_HEX_TAG )
        . "</script>\n";
}

The dates use get_post_time( 'c', true ): ISO 8601 in GMT with the offset, as Google expects. JSON_HEX_TAG encodes < and >, so a title containing </script> cannot end the block. Do not run esc_html() on the values: the JSON encoder escapes what is needed, and HTML entities would show up literally in the search result.

The breadcrumb trail

function ha_breadcrumb_schema( $post ) {
    $items = [ [ 'name' => get_bloginfo( 'name' ), 'item' => home_url( '/' ) ] ];

    $categories = get_the_category( $post->ID );
    if ( $categories ) {
        $items[] = [ 'name' => $categories[0]->name, 'item' => get_category_link( $categories[0] ) ];
    }
    $items[] = [ 'name' => wp_strip_all_tags( get_the_title( $post ) ), 'item' => get_permalink( $post ) ];

    $list = [];
    foreach ( $items as $i => $item ) {
        $list[] = [ '@type' => 'ListItem', 'position' => $i + 1 ] + $item;
    }
    return [ '@type' => 'BreadcrumbList', 'itemListElement' => $list ];
}

The trail in the JSON should match the breadcrumb that visitors see on the page; Google may ignore markup that describes something not visible.

Check it

Open the post in the Rich Results Test (search.google.com/test/rich-results) or the Schema Markup Validator (validator.schema.org). The first shows which rich results the page qualifies for, the second checks the schema.org vocabulary in general.

NOTE: If an SEO plugin is activated later, it outputs its own graph for the same page. Two different BlogPosting blocks are confusing; remove the theme function then. An FAQ block works the same way with FAQPage, Question and acceptedAnswer, but only for questions that are visible on the page.

Update (2023): In August 2023 Google limited FAQ rich results to well-known government and health sites. FAQPage markup is still valid, but on most sites it no longer produces the expandable questions in the search results.