跳到正文
DEV Community· Istiak Ahamed·· 50 分鐘前AI 評分52

如何為 WordPress 加入 JSON-LD Schema 標記而不依賴 SEO 外掛

Add Schema Markup to WordPress Without Plugin: JSON-LD

AI 導讀

文章示範以 PHP 陣列建立 JSON-LD @graph,透過 WordPress 的 wp_head 輸出並以 wp_json_encode() 序列化;完整實作採用 Must-Use plugin,不依賴 SEO 外掛。

正文

Most WordPress schema plugins load an admin dashboard, register custom database tables, and still output disconnected JSON-LD fragments that collide with your theme or WooCommerce defaults. Learning how to add schema markup to WordPress without plugin dependencies lets you emit a single, connected @graph payload in wp_head using native PHP arrays and wp_json_encode(). Below is the complete code architecture for generating Organization, WebSite, BlogPosting, Person, and BreadcrumbList structured data conditionally per template—without syntax errors, duplicate graphs, or plugin bloat.

Table of Contents


Quick Answer: Output a Safe JSON-LD Graph in wp_head

Never concatenate JSON strings by hand with echo '{"headline": "' . get_the_title() . '"}'. An unescaped double quote or newline in a post title will immediately break the JSON parser. Instead, build a PHP associative array and serialize it with wp_json_encode():

<?php
/**
 * Plugin Name: Kinetix Native JSON-LD Schema
 * Description: Outputs clean Organization and BlogPosting JSON-LD in wp_head.
 */

defined( 'ABSPATH' ) || exit;

add_action( 'wp_head', function (): void {
    if ( is_admin() || is_feed() || is_404() ) {
        return;
    }

    $site_url = home_url( '/' );
    $org_id   = $site_url . '#organization';
    $graph    = array(
        array(
            '@type' => 'Organization',
            '@id'   => $org_id,
            'name'  => get_bloginfo( 'name' ),
            'url'   => $site_url,
        ),
    );

    if ( is_singular( 'post' ) ) {
        $post    = get_queried_object();
        $post_url = get_permalink( $post );
        $graph[] = array(
            '@type'            => 'BlogPosting',
            '@id'              => $post_url . '#article',
            'headline'         => get_the_title( $post ),
            'datePublished'    => get_the_date( DATE_W3C, $post ),
            'dateModified'     => get_the_modified_date( DATE_W3C, $post ),
            'mainEntityOfPage' => $post_url,
            'author'           => array(
                '@type' => 'Person',
                'name'  => get_the_author_meta( 'display_name', (int) $post->post_author ),
            ),
            'publisher'        => array( '@id' => $org_id ),
        );
    }

    $payload = array(
        '@context' => 'https://schema.org',
        '@graph'   => $graph,
    );

    printf(
        "<script type=\"application/ld+json\">\n%s\n</script>\n",
        wp_json_encode( $payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE )
    );
}, 20 );

Passing JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE keeps URLs readable (https://example.com/ instead of https:\/\/example.com\/), while wp_json_encode() handles UTF-8 validation and quote escaping automatically.


Why JSON-LD Beats Inline Microdata in Modern WordPress Themes

Older WordPress themes scattered itemscope, itemtype="https://schema.org/Article", and itemprop="headline" attributes across dozens of PHP template files. In a modern block theme or component-driven PHP theme, inline microdata creates brittle coupling between your visual HTML and your structured data.

Engineering Dimension JSON-LD in wp_head (application/ld+json) Inline HTML Microdata (itemscope / itemprop)
Template Coupling Zero. Generated in one central PHP hook completely separate from block markup. High. Changing a wrapper <div> or block template can break required property nesting.
Entity Linking (@id) Native @graph references. One #organization node can be referenced by #website and #article. Verbose itemref attributes that frequently break across template parts.
Escaping & Safety Serialized once via wp_json_encode() with guaranteed valid JSON syntax. Spread across multiple esc_attr() calls inside HTML templates.
Google Search Preference Explicitly recommended by Google Search Central. Supported, but harder to maintain and debug.

When you use a single JSON-LD @graph array in wp_head, every entity on the page carries a stable @id URI (such as https://example.com/#organization or https://example.com/blog/post-slug#article). That allows the BlogPosting node to point its publisher property directly to {"@id": "https://example.com/#organization"} without repeating the organization's logo, social URLs, and contact metadata on every post.


What Google Search Central Actually Supports for Rich Results

Before writing schema code, it is important to separate Schema.org vocabulary completeness from Google Search rich result eligibility. The Schema.org vocabulary (schema.org) defines hundreds of types, while Google Search only uses a specific subset to generate visual enhancements (Rich Results) in SERPs.

Let's be honest about what structured data can and cannot do:

  1. Structured data enables eligibility, not a guarantee. Even when your JSON-LD passes Google's Rich Results Test with zero warnings, Google decides whether to display rich snippets based on query intent, site authority, and content parity.
  2. Google retired or restricted several popular rich result types. Since August 2023, Google restricts FAQPage rich results in search to authoritative government and health websites, and completely deprecated HowTo rich results. You can still emit FAQPage JSON-LD if you want clear machine-readable Q&A pairs for other engines or AI parsers, but do not expect an expandable FAQ accordion in Google Search for a commercial or developer blog.
  3. Visible content parity is mandatory. Every property in your JSON-LD must match content visible to a human reader on the rendered HTML page. Emitting 5-star AggregateRating markup on a page that does not display real user reviews violates Google's structured data spam policies.

Here are the core schema types that remain high-value for WordPress blogs, studios, software vendors, and academic sites according to the Google Search Gallery:

Schema.org Type Where to Output It Required / Recommended Properties Search & Discovery Purpose
Organization Site-wide (or Front Page + @id reference) name, url, logo (ImageObject), sameAs, contactPoint Knowledge Graph entity reconciliation, brand logo, and social profile linking.
WebSite Site-wide (#website) name, url, publisher (@id to #organization) Defines the site entity and links it to the publishing organization.
Article / BlogPosting Single posts (is_singular('post')) headline, image, datePublished, dateModified, author (Person with name and url), publisher Headline, thumbnail, publish/update timestamp, and author attribution in Google Search and Discover.
BreadcrumbList All hierarchical pages, posts, and CPTs itemListElement array of ListItem (position, name, item) Replaces raw URLs with structured breadcrumb trails in search snippets.
ProfilePage + Person Author archives (is_author()) mainEntity (Person with name, jobTitle, sameAs, description) Connects articles to verified human author profiles (E-E-A-T entity disambiguation).
SoftwareApplication Product pages (e.g., themes/plugins) name, operatingSystem, applicationCategory, offers (Offer with price, priceCurrency) Software price, currency, and platform details in search results.
ScholarlyArticle Research papers (is_singular('kx_research')) headline, author, datePublished, identifier (DOI), sameAs Complements Google Scholar Highwire Press meta tags for general web search.

Execution Flow: Conditional Schema Output in WordPress

To keep your HTML <head> lean and accurate, your PHP schema generator should inspect the current template context on wp_head, assemble only the nodes that belong on that URL, and print a single <script type="application/ld+json"> tag.

flowchart TD
    A["Action: wp_head (Priority 20)"] --> B{"Is Admin, Feed, 404, or SEO Plugin Schema Active?"}
    B -- "Yes" --> C["Abort (Output Nothing)"]
    B -- "No" --> D["Initialize @graph with Organization (#organization) & WebSite (#website)"]
    D --> E{"Check Template Context"}
    E -- "is_singular('post')" --> F["Append BlogPosting (#article) + Author Person + BreadcrumbList"]
    E -- "is_singular('kx_project')" --> G["Append CreativeWork + BreadcrumbList"]
    E -- "is_author()" --> H["Append ProfilePage + Person (#author)"]
    E -- "is_page() or is_archive()" --> I["Append WebPage / CollectionPage + BreadcrumbList"]
    F --> J["Apply Filter: kx_schema_graph"]
    G --> J
    H --> J
    I --> J
    J --> K["Serialize via wp_json_encode() and print <script type='application/ld+json'>"]

How to Add Schema Markup to WordPress Without Plugin Code

Let's build a complete, modular Must-Use plugin at wp-content/mu-plugins/kx-schema-graph.php. It outputs a unified @graph containing Organization, WebSite, BreadcrumbList, BlogPosting, and ProfilePage on the right routes, pulls the featured image dimensions via wp_get_attachment_image_src(), and exposes a kx_schema_graph filter so custom post types can append their own nodes.

<?php
/**
 * Plugin Name: Kinetix Unified JSON-LD Schema Graph
 * Description: Emits Organization, WebSite, BlogPosting, ProfilePage, and BreadcrumbList JSON-LD without an SEO plugin.
 * Version:     1.1.0
 * Author:      Kinetix
 * License:     GPL-2.0-or-later
 */

defined( 'ABSPATH' ) || exit;

/**
 * Build the Organization node for the current site.
 *
 * @return array<string, mixed>
 */
function kx_schema_organization_node(): array {
    $site_url = home_url( '/' );
    $node     = array(
        '@type' => 'Organization',
        '@id'   => $site_url . '#organization',
        'name'  => get_bloginfo( 'name' ),
        'url'   => $site_url,
    );

    $custom_logo_id = (int) get_theme_mod( 'custom_logo' );
    if ( $custom_logo_id > 0 ) {
        $logo_src = wp_get_attachment_image_src( $custom_logo_id, 'full' );
        if ( is_array( $logo_src ) && ! empty( $logo_src[0] ) ) {
            $node['logo'] = array(
                '@type'  => 'ImageObject',
                '@id'    => $site_url . '#logo',
                'url'    => $logo_src[0],
                'width'  => (int) $logo_src[1],
                'height' => (int) $logo_src[2],
            );
        }
    }

    return $node;
}

/**
 * Build the WebSite node linked to #organization.
 *
 * @return array<string, mixed>
 */
function kx_schema_website_node(): array {
    $site_url = home_url( '/' );
    return array(
        '@type'       => 'WebSite',
        '@id'         => $site_url . '#website',
        'url'         => $site_url,
        'name'        => get_bloginfo( 'name' ),
        'description' => get_bloginfo( 'description' ),
        'inLanguage'  => get_bloginfo( 'language' ),
        'publisher'   => array(
            '@id' => $site_url . '#organization',
        ),
    );
}

/**
 * Build the BlogPosting and Author Person nodes for a single post.
 *
 * @param WP_Post $post Current post object.
 * @return array<int, array<string, mixed>>
 */
function kx_schema_article_nodes( WP_Post $post ): array {
    $site_url   = home_url( '/' );
    $post_url   = (string) get_permalink( $post );
    $author_id  = (int) $post->post_author;
    $author_url = get_author_posts_url( $author_id );
    $person_id  = $author_url . '#person';

    $excerpt = has_excerpt( $post )
        ? wp_strip_all_tags( $post->post_excerpt )
        : wp_trim_words( wp_strip_all_tags( $post->post_content ), 28, '...' );

    $article = array(
        '@type'            => 'BlogPosting',
        '@id'              => $post_url . '#article',
        'isPartOf'         => array( '@id' => $site_url . '#website' ),
        'mainEntityOfPage' => array(
            '@type' => 'WebPage',
            '@id'   => $post_url,
        ),
        'headline'         => wp_strip_all_tags( get_the_title( $post ) ),
        'description'      => $excerpt,
        'datePublished'    => get_the_date( DATE_W3C, $post ),
        'dateModified'     => get_the_modified_date( DATE_W3C, $post ),
        'inLanguage'       => get_bloginfo( 'language' ),
        'author'           => array( '@id' => $person_id ),
        'publisher'        => array( '@id' => $site_url . '#organization' ),
    );

    // Attach featured image if present.
    $thumb_id = (int) get_post_thumbnail_id( $post );
    if ( $thumb_id > 0 ) {
        $img = wp_get_attachment_image_src( $thumb_id, 'full' );
        if ( is_array( $img ) && ! empty( $img[0] ) ) {
            $article['image'] = array(
                '@type'  => 'ImageObject',
                'url'    => $img[0],
                'width'  => (int) $img[1],
                'height' => (int) $img[2],
            );
        }
    }

    // Attach primary category as articleSection.
    $categories = get_the_category( $post->ID );
    if ( ! empty( $categories ) && isset( $categories[0]->name ) ) {
        $article['articleSection'] = $categories[0]->name;
    }

    $person = array(
        '@type' => 'Person',
        '@id'   => $person_id,
        'name'  => get_the_author_meta( 'display_name', $author_id ),
        'url'   => $author_url,
    );

    $bio = trim( (string) get_the_author_meta( 'description', $author_id ) );
    if ( '' !== $bio ) {
        $person['description'] = $bio;
    }

    return array( $article, $person );
}

Building Dynamic BreadcrumbList JSON-LD for Posts and Custom Post Types

Google uses BreadcrumbList structured data to show the page's hierarchy in search results (example.com › Projects › Obsidian Design System). If your site registers custom post types with has_archive—like the kx_project type we built in our WordPress custom post type without a plugin guide—your breadcrumb generator should automatically insert the post type archive link at position 2 and the single item at position 3.

Add this function to wp-content/mu-plugins/kx-schema-graph.php:

/**
 * Build a BreadcrumbList node for singular posts, pages, and custom post types.
 *
 * @return array<string, mixed>|null
 */
function kx_schema_breadcrumb_node(): ?array {
    if ( is_front_page() || is_home() ) {
        return null;
    }

    $items    = array();
    $position = 1;

    // Position 1: Home
    $items[] = array(
        '@type'    => 'ListItem',
        'position' => $position++,
        'name'     => __( 'Home', 'kx-schema' ),
        'item'     => home_url( '/' ),
    );

    if ( is_singular( 'post' ) ) {
        $post       = get_queried_object();
        $categories = get_the_category( $post->ID );
        if ( ! empty( $categories ) ) {
            $primary_cat = $categories[0];
            $items[]     = array(
                '@type'    => 'ListItem',
                'position' => $position++,
                'name'     => $primary_cat->name,
                'item'     => get_category_link( $primary_cat->term_id ),
            );
        }
        $items[] = array(
            '@type'    => 'ListItem',
            'position' => $position++,
            'name'     => wp_strip_all_tags( get_the_title( $post ) ),
            'item'     => (string) get_permalink( $post ),
        );
    } elseif ( is_singular() ) {
        $post      = get_queried_object();
        $post_type = get_post_type_object( (string) get_post_type( $post ) );

        // If this is a Custom Post Type with an archive (e.g., Projects or Research), add the archive crumb.
        if ( $post_type && ! $post_type->_builtin && $post_type->has_archive ) {
            $archive_link = get_post_type_archive_link( $post_type->name );
            if ( is_string( $archive_link ) && '' !== $archive_link ) {
                $items[] = array(
                    '@type'    => 'ListItem',
                    'position' => $position++,
                    'name'     => $post_type->labels->name,
                    'item'     => $archive_link,
                );
            }
        }

        // If this is a hierarchical child Page, walk its ancestors from root to parent.
        if ( is_page( $post ) && $post->post_parent > 0 ) {
            $ancestors = array_reverse( get_post_ancestors( $post ) );
            foreach ( $ancestors as $ancestor_id ) {
                $items[] = array(
                    '@type'    => 'ListItem',
                    'position' => $position++,
                    'name'     => wp_strip_all_tags( get_the_title( $ancestor_id ) ),
                    'item'     => (string) get_permalink( $ancestor_id ),
                );
            }
        }

        $items[] = array(
            '@type'    => 'ListItem',
            'position' => $position++,
            'name'     => wp_strip_all_tags( get_the_title( $post ) ),
            'item'     => (string) get_permalink( $post ),
        );
    }

    if ( count( $items ) < 2 ) {
        return null;
    }

    return array(
        '@type'           => 'BreadcrumbList',
        'itemListElement' => $items,
    );
}

Extending Schema With Native Custom Fields

When you store structured metadata using native post meta (as covered in our WordPress custom fields without a plugin tutorial), you can feed those values directly into your JSON-LD graph. For example, on a research paper post type (kx_research), you can read _kx_doi and _kx_journal_title from get_post_meta() and output a ScholarlyArticle node alongside your Google Scholar citation meta tags—which is the exact approach packaged inside Kinetix Scholar & SEO Pro.


Preventing Duplicate Schema When an SEO Plugin Is Active

What if you build a theme or functionality plugin for client sites where someone might activate Yoast SEO, Rank Math, or The SEO Framework later? Emitting two conflicting Article or BreadcrumbList graphs on the same URL confuses validators and can cause Search Console warnings.

Always add a lightweight conflict check before printing your custom JSON-LD:

/**
 * Check whether a major third-party SEO plugin is already handling JSON-LD output.
 */
function kx_third_party_schema_active(): bool {
    return defined( 'WPSEO_VERSION' )                  // Yoast SEO
        || defined( 'RANK_MATH_VERSION' )              // Rank Math
        || defined( 'THE_SEO_FRAMEWORK_VERSION' )      // The SEO Framework
        || defined( 'SEOPRESS_VERSION' )               // SEOPress
        || defined( 'AIOSEO_VERSION' );                // All in One SEO
}

/**
 * Assemble and print the complete JSON-LD @graph in wp_head.
 */
add_action(
    'wp_head',
    function (): void {
        if ( is_admin() || is_feed() || is_404() || is_search() ) {
            return;
        }

        if ( kx_third_party_schema_active() && ! apply_filters( 'kx_force_native_schema', false ) ) {
            return;
        }

        $graph = array(
            kx_schema_organization_node(),
            kx_schema_website_node(),
        );

        if ( is_singular( 'post' ) ) {
            $queried = get_queried_object();
            if ( $queried instanceof WP_Post ) {
                foreach ( kx_schema_article_nodes( $queried ) as $node ) {
                    $graph[] = $node;
                }
            }
        }

        $breadcrumbs = kx_schema_breadcrumb_node();
        if ( null !== $breadcrumbs ) {
            $graph[] = $breadcrumbs;
        }

        /**
         * Filter the assembled JSON-LD @graph array before encoding.
         *
         * @param array<int, array<string, mixed>> $graph Schema graph nodes.
         */
        $graph = apply_filters( 'kx_schema_graph', $graph );
        if ( empty( $graph ) ) {
            return;
        }

        $payload = array(
            '@context' => 'https://schema.org',
            '@graph'   => array_values( $graph ),
        );

        printf(
            "\n<script type=\"application/ld+json\" class=\"kx-schema-graph\">\n%s\n</script>\n",
            wp_json_encode( $payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE )
        );
    },
    20
);

Validating Your Output With Rich Results Test and Schema.org

Never ship JSON-LD changes without running three verification passes:

  1. Local JSON syntax linting: Before testing in a browser, verify that every <script type="application/ld+json"> block on your staging site parses cleanly:
   curl -s https://example.com/blog/sample-post/ \
     | sed -n '/<script type="application\/ld+json"/,/<\/script>/p' \
     | sed '1d;$d' \
     | jq .

If jq . prints formatted JSON with exit code 0, your escaping and UTF-8 encoding are valid.

  1. Google Rich Results Test: Checks strictly for Google Search rich result eligibility (Article, BreadcrumbList, SoftwareApplication, ProfilePage) and highlights missing required properties or date format issues.
  2. Schema Markup Validator (validator.schema.org): Validates the complete Schema.org graph structure, @id entity references, and types that do not trigger Google visual snippets (such as ScholarlyArticle or WebSite).

For AI agents and developer documentation crawlers that inspect your site alongside search engines, pair your JSON-LD structured data with our guide on how to add llms.txt to WordPress without a plugin.

Troubleshooting: Rich Results Test reports "Missing field 'image'" on BlogPosting

Google recommends an image of at least 1200 pixels wide for Article and BlogPosting objects to qualify for Google Discover and Top Stories surfaces. If a post does not have a featured image (get_post_thumbnail_id() returns 0), fall back to your site's default Open Graph cover image (for example, home_url( '/wp-content/themes/your-theme/assets/og-default.png' )) so the image property is never omitted on published articles.

Troubleshooting: Unescaped HTML entities (’ or &) inside JSON-LD headline

WordPress's get_the_title() runs wptexturize(), which turns straight apostrophes into HTML entities like ’ or &amp;. If you prefer raw Unicode punctuation inside your JSON-LD strings, wrap the stripped title in html_entity_decode( wp_strip_all_tags( get_the_title( $post ) ), ENT_QUOTES, 'UTF-8' ) before passing the array to wp_json_encode().


Frequently Asked Questions

Where should JSON-LD schema markup be placed in WordPress?

Hook your output function into wp_head so the <script type="application/ld+json"> block renders inside the HTML <head>. While Google can also parse JSON-LD placed in the <body>, outputting it in wp_head keeps all document metadata (canonical URL, Open Graph tags, and structured data) in one predictable location.

Can I have multiple application/ld+json script tags on the same WordPress page?

Yes. Both Googlebot and the Schema.org validator parse multiple <script type="application/ld+json"> blocks on a single page. However, combining your own entities into a single @graph array with shared @id pointers is cleaner and avoids repeating your Organization and Person blocks across separate script tags.

Why did my FAQ schema stop showing dropdowns in Google Search?

In August 2023, Google updated its FAQ structured data policy to display FAQPage rich results only for well-known, authoritative government and health websites. Even with valid FAQPage JSON-LD, general business, SaaS, and developer blogs will not see expandable FAQ snippets in Google SERPs.

Does WooCommerce already output Product schema automatically?

Yes. WooCommerce core automatically generates Product and BreadcrumbList JSON-LD via its WC_Structured_Data class on single product pages (is_product()). If you write a custom schema hook for a site running WooCommerce, skip custom Article output when function_exists( 'is_woocommerce' ) && is_woocommerce() returns true so you do not conflict with WooCommerce's native product offers.


Originally published at https://kinetix.software/blog/wordpress-schema-markup-without-plugin.

來源:DEV Community · dev.to