MENU

問い合わせ

    お問い合わせ


    【WordPressで作るキュレーションメディア 第8回】目次と構造化データ(JSON-LD: Article / BreadcrumbList / ItemList)

    (2026年10月29日 追記:記事どおりに再現できるよう、必要なコードと手順を追加しました)

    長いまとめ記事では、読者が「自分の知りたい項目まで飛べる」目次があると読みやすくなります。また、検索エンジンに「これは記事で、著者は誰で、サイトのどの位置にあるページか」を機械が読める形で伝えるのが構造化データです。どちらも「WordPress 構造化データ」「目次 自動生成」などで調べると多くのプラグインが見つかりますが、仕組みを理解しておかないと、表示と中身がずれたまま気づけません。

    「目次と構造化データを入れたい。構造化データを入れれば検索結果で目立つようになるの?」

    結論から言うと、目次は見出しの id と目次のリンクを「同じ HTML」から作り、構造化データは画面に表示している内容と同じデータ源から作るのが、ずれを防ぐいちばん確実な方法です。そして、構造化データは内容を正確に伝えるための実装で、リッチリザルト(=検索結果での特別な表示)が出ることは保証されません。これは Google 自身がドキュメントで明記しています。

    前回の第7回では、人気記事ランキングと関連記事を作りました。第8回の今回は、目次ブロック、パンくずリスト、JSON-LD の出力をプラグインに追加します。

    目次

    今回のゴールと、構造化データでできること・できないこと

    完成すると、記事ページは次のようになります。

    • タイトルの上にパンくずリスト(ホーム / カテゴリ / 記事タイトル)が表示される
    • 本文に「目次」ブロックを置くと、h2・h3 の見出しへのリンク一覧が表示される(h3 は直前の h2 の下に入れ子)
    • <head> に JSON-LD(=構造化データを JSON で書く形式)が出力される。記事は Article と BreadcrumbList、まとめ・ランキング記事はそれに加えて ItemList

    3種類の構造化データと Google の扱い(2025年9月時点)

    Google 検索セントラルのドキュメント(2025年9月時点の版を確認)での扱いを整理すると、次のとおりです。

    種類何を表すかGoogle のドキュメントでの位置付け
    Article記事のタイトル・著者・公開日・更新日・画像必須プロパティはなく、該当する推奨プロパティ(author・datePublished・dateModified・headline・image)をできるだけ追加する
    BreadcrumbListサイト内でのページの位置ListItem を2つ以上含め、各項目に position・name・item(URL)を入れる。最後の項目の item は省略可
    ItemListページ内の項目の並びカルーセル(横にスワイプする表示)の対象は、コースリスト・映画・レシピ・レストランと組み合わせた場合のみ

    ここで大事なのは ItemList です。まとめ記事に ItemList を付けても、Google のカルーセル表示の対象にはなりません。今回 ItemList を出すのは、「このページは順番のある項目の一覧である」という構造を正確に表すためで、特定の表示を狙ったものではありません。

    📰 出典:Google 検索セントラル「カルーセル(ItemList)の構造化データ」

    また、構造化データの一般的なガイドラインには、正しくマークアップしても検索結果に表示されるとは限らないこと、ページの読者に表示されない内容をマークアップしてはいけないことが書かれています。今回、パンくずリストを画面にも表示するようにしたのはこのためです。

    📰 出典:Google 検索セントラル「構造化データに関する一般的なガイドライン」

    今回追加・変更したファイル

    ファイル内容
    プラグイン includes/toc.php見出しへの id 付与と目次の差し込み(新規)
    プラグイン blocks/toc/目次ブロック(新規。表示は差し込み位置の目印だけ)
    プラグイン includes/schema.phpパンくずの項目作成と JSON-LD の出力(新規)
    プラグイン blocks/breadcrumb/パンくずリストブロック(新規)
    プラグイン curation-tools.php読み込み・ブロック登録、バージョン 0.8.0
    テーマ templates/single*.html・style.css3つの記事テンプレートの先頭にパンくずを追加、バージョン 0.8.0

    この回で新しく使うフォルダを作ります(プロジェクトのフォルダで実行)。

    mkdir -p wp-content/plugins/curation-tools/blocks/breadcrumb \
      wp-content/plugins/curation-tools/blocks/toc

    企画の段階では「目次と JSON-LD」だけの予定でしたが、上に書いたガイドラインに合わせるため、パンくずリストの表示ブロックを追加しました。

    目次:見出しの id とリンクを同じ HTML から作る

    目次で最もよく起きる不具合は、「目次のリンク先の id」と「見出しに付いた id」がずれて、クリックしても移動しないことです。目次を作る処理と見出しに id を付ける処理を別々に書くと、見出しの数え方が少し違うだけでずれてしまいます。

    そこで今回は、本文の HTML が組み立て終わった後に1回だけ処理し、見出しへの id 付与と目次の作成を同時に行うようにしました。目次ブロック自体は「ここに目次を入れる」という目印を出すだけです。

    順番処理
    1本文のブロックが HTML に変換される(目次ブロックは目印のコメントを含む <nav> を出力)
    2the_content フィルター(優先度 20)で、本文の h2・h3 に id を付けながら見出しの文字を集める
    3目印の位置に、集めた見出しへのリンク一覧を差し込む。見出しが2つ未満なら目次ごと取り除く

    wp-content/plugins/curation-tools/includes/toc.php(curation_tools_toc_add_anchors() の抜粋。既存の id を集める1回目の処理と、見出し終了時の処理を省略)

    $processor = new WP_HTML_Tag_Processor( $html );
    while ( $processor->next_token() ) {
    	$name = $processor->get_token_name();
    
    	if ( 'H2' === $name || 'H3' === $name ) {
    		// (閉じタグのときは、集めた文字を $items に追加して continue)
    
    		$id = $processor->get_attribute( 'id' );
    		if ( ! is_string( $id ) || '' === $id ) {
    			do {
    				++$number;
    				$id = 'toc-' . $number;
    			} while ( isset( $used[ $id ] ) );
    			$used[ $id ] = true;
    			$processor->set_attribute( 'id', $id );
    		}
    		$current = array(
    			'id'    => $id,
    			'level' => 'H2' === $name ? 2 : 3,
    			'text'  => '',
    		);
    		continue;
    	}
    
    	// 見出しの中の文字だけを集める(<strong> などのタグは無視し、文字参照はデコード済みの値になる)。
    	if ( null !== $current && '#text' === $processor->get_token_type() ) {
    		$current['text'] .= $processor->get_modifiable_text();
    	}
    }

    WP_HTML_Tag_Processor は WordPress に組み込まれている HTML の読み取り・書き換え用のクラスです。正規表現で HTML を書き換えると、属性の書き方の違いや入れ子で壊れやすいのですが、このクラスを使うとタグ単位で安全に属性を追加できます。

    📰 出典:WordPress Developer Resources「WP_HTML_Tag_Processor」

    id の決め方は次のとおりです。

    • 編集者がブロックの「HTML アンカー」で id を指定した見出しは、その id をそのまま使う
    • それ以外の見出しには toc-1、toc-2 … を順に付ける。本文中で既に使われている id とは重ならないようにする
    • 目次には見出しの文字だけを使い、<strong> などの装飾は外す。出力時は esc_html() と esc_attr() でエスケープする

    includes/toc.php の全文です。上の抜粋で省略した既存の id を集める処理と見出し終了時の処理、目次のリスト(h2 の下に h3 を入れ子にする)を作る関数、the_content フィルターを含みます。

    wp-content/plugins/curation-tools/includes/toc.php の全文(161行・新規)
    <?php
    /**
     * 目次: 本文の見出し(h2・h3)にアンカー(id)を付け、目次ブロックの位置に見出しの一覧を差し込む。
     *
     * 見出しの id と目次のリンク先を必ず一致させるため、両方を「表示用に組み立て終わった本文の HTML」
     * から作る(the_content の最後の方で1回だけ処理する)。目次ブロック(blocks/toc)自体は、
     * 差し込み位置の目印を出力するだけ。
     *
     * @package Curation_Tools
     */
    
    if ( ! defined( 'ABSPATH' ) ) {
    	exit;
    }
    
    define( 'CURATION_TOOLS_TOC_MARKER', '<!--curation-toc-->' );
    
    /**
     * 本文の h2・h3 に id を付け、見出しの一覧を返す。
     *
     * 編集者がブロックの「HTML アンカー」で id を指定した見出しはその id を使い、
     * それ以外には toc-1, toc-2 … を順に付ける(本文中の既存の id と重複しないようにする)。
     *
     * @param string $html 本文の HTML。
     * @return array{html: string, items: array<int, array{id: string, level: int, text: string}>}
     */
    function curation_tools_toc_add_anchors( $html ) {
    	// 1回目: 既に使われている id を集める(自動で付ける id と重複させないため)。
    	$used      = array();
    	$processor = new WP_HTML_Tag_Processor( $html );
    	while ( $processor->next_tag() ) {
    		$id = $processor->get_attribute( 'id' );
    		if ( is_string( $id ) && '' !== $id ) {
    			$used[ $id ] = true;
    		}
    	}
    
    	// 2回目: 見出しに id を付けながら、見出しの文字列を取り出す。
    	$items     = array();
    	$current   = null;
    	$number    = 0;
    	$processor = new WP_HTML_Tag_Processor( $html );
    	while ( $processor->next_token() ) {
    		$name = $processor->get_token_name();
    
    		if ( 'H2' === $name || 'H3' === $name ) {
    			if ( $processor->is_tag_closer() ) {
    				if ( null !== $current ) {
    					$current['text'] = trim( preg_replace( '/\s+/u', ' ', $current['text'] ) );
    					if ( '' !== $current['text'] ) {
    						$items[] = $current;
    					}
    					$current = null;
    				}
    				continue;
    			}
    
    			$id = $processor->get_attribute( 'id' );
    			if ( ! is_string( $id ) || '' === $id ) {
    				do {
    					++$number;
    					$id = 'toc-' . $number;
    				} while ( isset( $used[ $id ] ) );
    				$used[ $id ] = true;
    				$processor->set_attribute( 'id', $id );
    			}
    			$current = array(
    				'id'    => $id,
    				'level' => 'H2' === $name ? 2 : 3,
    				'text'  => '',
    			);
    			continue;
    		}
    
    		// 見出しの中の文字だけを集める(<strong> などのタグは無視し、文字参照はデコード済みの値になる)。
    		if ( null !== $current && '#text' === $processor->get_token_type() ) {
    			$current['text'] .= $processor->get_modifiable_text();
    		}
    	}
    
    	return array(
    		'html'  => $processor->get_updated_html(),
    		'items' => $items,
    	);
    }
    
    /**
     * 見出しの一覧から目次のリスト(h3 は直前の h2 の下に入れ子)を組み立てる。
     *
     * @param array $items curation_tools_toc_add_anchors() の items。
     * @return string
     */
    function curation_tools_toc_render_list( $items ) {
    	$html     = '<ol class="curation-toc__list">';
    	$open_h2  = false;
    	$open_sub = false;
    
    	foreach ( $items as $item ) {
    		$link = sprintf( '<a href="#%1$s">%2$s</a>', esc_attr( $item['id'] ), esc_html( $item['text'] ) );
    
    		if ( 3 === $item['level'] && $open_h2 ) {
    			if ( ! $open_sub ) {
    				$html    .= '<ol>';
    				$open_sub = true;
    			}
    			$html .= '<li>' . $link . '</li>';
    			continue;
    		}
    
    		if ( $open_sub ) {
    			$html    .= '</ol>';
    			$open_sub = false;
    		}
    		if ( $open_h2 ) {
    			$html .= '</li>';
    		}
    		// 最初の h2 より前にある h3 は、h2 と同じ階層に並べる。
    		$html   .= '<li>' . $link;
    		$open_h2 = 2 === $item['level'];
    		if ( ! $open_h2 ) {
    			$html .= '</li>';
    		}
    	}
    
    	if ( $open_sub ) {
    		$html .= '</ol>';
    	}
    	if ( $open_h2 ) {
    		$html .= '</li>';
    	}
    	return $html . '</ol>';
    }
    
    /**
     * 記事ページの本文に見出しアンカーと目次を適用する。
     *
     * do_blocks(優先度 9)・ショートコード(11)の後に動かし、ブロックの表示が済んだ HTML を扱う。
     *
     * @param string $content 本文の HTML。
     * @return string
     */
    function curation_tools_toc_filter_content( $content ) {
    	if ( ! is_singular( 'post' ) || get_the_ID() !== get_queried_object_id() ) {
    		return $content;
    	}
    
    	$result  = curation_tools_toc_add_anchors( $content );
    	$content = $result['html'];
    
    	if ( false === strpos( $content, CURATION_TOOLS_TOC_MARKER ) ) {
    		return $content;
    	}
    
    	// 見出しが2つ未満なら目次は不要なので、目次ブロックごと取り除く。
    	if ( count( $result['items'] ) < 2 ) {
    		return preg_replace( '#<nav\b[^>]*\bdata-curation-toc\b[^>]*>.*?</nav>#s', '', $content );
    	}
    
    	return str_replace( CURATION_TOOLS_TOC_MARKER, curation_tools_toc_render_list( $result['items'] ), $content );
    }
    add_filter( 'the_content', 'curation_tools_toc_filter_content', 20 );

    目次ブロックの render.php は、差し込み位置の目印(HTML コメント)を含む <nav aria-label="目次"> だけを出力します。見出し用のタグ(h2)を使わず「目次」を <p> にしているのは、目次の見出し自体が目次に載ってしまわないようにするためです。

    wp-content/plugins/curation-tools/blocks/toc/render.php(新規・全文)

    <?php
    /**
     * 目次: 公開ページでは差し込み位置の目印だけを出力する。
     *
     * 目次の中身(見出しへのリンク)は includes/toc.php が本文全体を見て差し込む。
     * 記事ページ以外(一覧・抜粋など)では何も出力しない。
     *
     * @package Curation_Tools
     */
    
    if ( ! defined( 'ABSPATH' ) ) {
    	exit;
    }
    
    if ( ! is_singular( 'post' ) ) {
    	return;
    }
    ?>
    <nav <?php echo get_block_wrapper_attributes(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?> aria-label="目次" data-curation-toc>
    	<p class="curation-toc__title">目次</p>
    	<?php echo CURATION_TOOLS_TOC_MARKER; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- 固定の HTML コメント。 ?>
    </nav>

    block.json では "multiple": false を指定し、1つの記事に目次ブロックを1つしか置けないようにしました。また、目次のリンクで移動したときに見出しが画面の端に貼り付かないよう、CSS の scroll-margin-top で少し余白を取っています。

    目次ブロックの残りのファイルです。エディターでは、置き場所が分かる表示だけを出します。

    wp-content/plugins/curation-tools/blocks/toc/block.json(新規・全文)

    {
    	"$schema": "https://schemas.wp.org/wp/6.8/block.json",
    	"apiVersion": 3,
    	"name": "curation-tools/toc",
    	"version": "0.8.0",
    	"title": "目次",
    	"category": "text",
    	"icon": "list-view",
    	"description": "本文の見出し(h2・h3)から目次を作る。本文の先頭付近に1つ置いて使う。見出しが2つ未満の記事では表示しない。",
    	"keywords": [ "目次", "見出し", "toc" ],
    	"textdomain": "curation-tools",
    	"supports": {
    		"html": false,
    		"multiple": false,
    		"reusable": false,
    		"spacing": {
    			"margin": true
    		}
    	},
    	"editorScript": "file:./index.js",
    	"style": "file:./style-index.css",
    	"render": "file:./render.php"
    }

    wp-content/plugins/curation-tools/blocks/toc/index.js(新規・全文)

    /**
     * 目次: ブロックの登録(エディター用)。
     *
     * 目次の中身は公開ページで本文の見出しから作るため、エディターでは説明だけを表示する。
     */
    import { registerBlockType } from '@wordpress/blocks';
    import { useBlockProps } from '@wordpress/block-editor';
    
    import metadata from './block.json';
    import './style.css';
    
    function Edit() {
    	return (
    		<nav { ...useBlockProps() } aria-label="目次">
    			<p className="curation-toc__title">目次</p>
    			<p>
    				本文の見出し(h2・h3)から、公開ページで目次が作られます。見出しが2つ未満のときは表示されません。
    			</p>
    		</nav>
    	);
    }
    
    registerBlockType( metadata.name, {
    	edit: Edit,
    } );

    wp-content/plugins/curation-tools/blocks/toc/style.css(新規・全文)

    /* 目次(フロントとエディターの両方に読み込まれる) */
    .wp-block-curation-tools-toc {
    	padding: var(--wp--preset--spacing--30) var(--wp--preset--spacing--40);
    	background: var(--wp--preset--color--accent-5, #f6f7f9);
    	font-size: var(--wp--preset--font-size--small, 0.875rem);
    }
    
    .wp-block-curation-tools-toc .curation-toc__title {
    	margin: 0 0 var(--wp--preset--spacing--20);
    	font-weight: 700;
    }
    
    .wp-block-curation-tools-toc ol {
    	margin: 0;
    	padding-left: 1.5em;
    }
    
    .wp-block-curation-tools-toc li {
    	padding-block: 0.125rem;
    }
    
    /* 目次のリンクで移動したとき、見出しが画面の上端に貼り付かないようにする */
    :where(.wp-block-post-content) :is(h2, h3)[id] {
    	scroll-margin-top: var(--wp--preset--spacing--40, 1.5rem);
    }

    パンくずと JSON-LD を同じ関数から作る

    パンくずリストは「ホーム → カテゴリ → 記事」の順です。この項目を作る関数を1つだけ用意し、画面のパンくずブロックと JSON-LD の両方から呼び出します。こうすれば、カテゴリ名を変えても表示と構造化データが必ず一致します。

    wp-content/plugins/curation-tools/includes/schema.php(curation_tools_get_breadcrumb_items() の抜粋)

    $categories = get_the_category( $post_id );
    if ( ! empty( $categories ) ) {
    	$category   = $categories[0];
    	$term_ids   = array_reverse( get_ancestors( $category->term_id, 'category', 'taxonomy' ) );
    	$term_ids[] = $category->term_id;
    	foreach ( $term_ids as $term_id ) {
    		$term = get_term( $term_id, 'category' );
    		$link = $term instanceof WP_Term ? get_term_link( $term ) : '';
    		if ( is_string( $link ) && '' !== $link ) {
    			$items[] = array(
    				'name' => $term->name,
    				'url'  => $link,
    			);
    		}
    	}
    }
    
    $items[] = array(
    	'name' => curation_tools_plain_text( get_the_title( $post_id ) ),
    	'url'  => get_permalink( $post_id ),
    );

    カテゴリが複数ある記事は、WordPress が返す順(名前順)の最初のカテゴリを使います。第2回で「カテゴリは少数固定、1記事1カテゴリを基本にする」と決めたので、通常はこれで困りません。

    Article:著者は画面の著者ボックスと同じ人を載せる

    Article には、Google のドキュメントで推奨されているプロパティのうち、このサイトで実際に表示している情報だけを入れます。

    includes/schema.php(curation_tools_build_schema() の抜粋)

    $article = array(
    	'@type'            => 'Article',
    	'@id'              => $permalink . '#article',
    	'mainEntityOfPage' => $permalink,
    	'headline'         => curation_tools_plain_text( get_the_title( $post ) ),
    	'datePublished'    => get_the_date( DATE_W3C, $post ),
    	'dateModified'     => get_the_modified_date( DATE_W3C, $post ),
    );
    
    if ( $author ) {
    	$person      = array(
    		'@type' => 'Person',
    		'name'  => $author->display_name,
    		'url'   => get_author_posts_url( $author->ID ),
    	);
    	$profile_url = (string) get_user_meta( $author->ID, 'curation_profile_url', true );
    	if ( '' !== $profile_url ) {
    		$person['sameAs'] = array( $profile_url );
    	}
    	$article['author'] = $person;
    }
    • 日付は DATE_W3C(ISO 8601 形式)で、+09:00 のようにタイムゾーンを含めます。Google のドキュメントでもタイムゾーンを含めることが推奨されています。
    • 著者は Person 型で、url に第6回で作った著者アーカイブ、sameAs にプロフィールの外部 URL(設定がある場合のみ)を入れます。Google のドキュメントでは、著者を一意に特定できるページへの URL を url か sameAs で示すことが強く推奨されています。
    • 画像はアイキャッチがある記事だけ入れます。

    📰 出典:Google 検索セントラル「記事(Article、NewsArticle、BlogPosting)の構造化データ」

    監修者は構造化データに入れていません。Google の Article のドキュメントには監修者を表すプロパティがなく、schema.org にある近いプロパティ(reviewedBy)は Article ではなく WebPage に対するものだからです。監修者の情報は、第6回の著者ボックスで画面に表示するだけにしています。

    ItemList:まとめリストの見出しを項目にする

    まとめ・ランキングのテンプレート(第3回)を使った記事では、第5回の「まとめリスト」パターン(class に curation-matome-list を持つグループ)の中にある見出しを集め、ItemList の項目名にします。本文のブロックを parse_blocks() で読み、グループの中を順にたどって見出しの文字を取り出しています。項目が2つ未満なら ItemList は出しません。

    JSON-LD を安全に出力する

    includes/schema.php(curation_tools_print_schema() の抜粋)

    $data = array(
    	'@context' => 'https://schema.org',
    	'@graph'   => curation_tools_build_schema( $post ),
    );
    $json = wp_json_encode( $data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP );
    if ( false === $json ) {
    	return;
    }
    
    wp_print_inline_script_tag( $json, array( 'type' => 'application/ld+json' ) );

    JSON を文字列の連結で組み立てると、記事タイトルに " が入っただけで壊れます。配列を作って wp_json_encode() で変換すれば、引用符などは正しくエスケープされます。

    さらに注意したいのが </script> です。JSON-LD は <script> タグの中に書くため、タイトルなどに「</script>」という文字列が含まれると、そこでタグが閉じてしまいます。JSON_HEX_TAG を指定すると < と > が Unicode のエスケープ表記(JSON として読み込むと元の文字に戻る書き方)に変換されるので、この問題を防げます。

    📰 出典:WordPress Developer Resources「wp_json_encode()」

    schema.php の全文と、パンくずリストのブロック

    includes/schema.php の全文です。上の3つの抜粋のほか、HTML を文字だけにする関数、まとめリストの見出しを集める関数を含みます。

    wp-content/plugins/curation-tools/includes/schema.php の全文(208行・新規)
    <?php
    /**
     * 構造化データ(JSON-LD): 記事ページに Article・BreadcrumbList を、まとめ/ランキング記事には
     * ItemList も出力する。
     *
     * 構造化データはページに表示されている内容と一致させる必要がある。パンくずは画面に表示する
     * パンくずブロック(blocks/breadcrumb)と同じ関数から作り、ItemList の項目名は本文の
     * まとめリスト(第5回のパターン)の見出しから取る。
     *
     * @package Curation_Tools
     */
    
    if ( ! defined( 'ABSPATH' ) ) {
    	exit;
    }
    
    /**
     * HTML を含む文字列を、構造化データ用のプレーンテキストにする。
     *
     * get_the_title() などは「&#8220;」のような文字参照を含むため、タグを除いてからデコードする。
     *
     * @param string $html 文字列。
     * @return string
     */
    function curation_tools_plain_text( $html ) {
    	return trim( html_entity_decode( wp_strip_all_tags( (string) $html ), ENT_QUOTES | ENT_HTML5, 'UTF-8' ) );
    }
    
    /**
     * 記事のパンくず(ホーム → カテゴリ(親から順)→ 記事)を返す。
     *
     * カテゴリが複数ある記事は、WordPress が返す順(名前順)の最初のカテゴリを使う。
     *
     * @param int $post_id 投稿ID。
     * @return array<int, array{name: string, url: string}>
     */
    function curation_tools_get_breadcrumb_items( $post_id ) {
    	$items = array(
    		array(
    			'name' => 'ホーム',
    			'url'  => home_url( '/' ),
    		),
    	);
    
    	$categories = get_the_category( $post_id );
    	if ( ! empty( $categories ) ) {
    		$category   = $categories[0];
    		$term_ids   = array_reverse( get_ancestors( $category->term_id, 'category', 'taxonomy' ) );
    		$term_ids[] = $category->term_id;
    		foreach ( $term_ids as $term_id ) {
    			$term = get_term( $term_id, 'category' );
    			$link = $term instanceof WP_Term ? get_term_link( $term ) : '';
    			if ( is_string( $link ) && '' !== $link ) {
    				$items[] = array(
    					'name' => $term->name,
    					'url'  => $link,
    				);
    			}
    		}
    	}
    
    	$items[] = array(
    		'name' => curation_tools_plain_text( get_the_title( $post_id ) ),
    		'url'  => get_permalink( $post_id ),
    	);
    	return $items;
    }
    
    /**
     * まとめリスト(class に curation-matome-list を持つグループ)の中の見出しを集める。
     *
     * @param array $blocks parse_blocks() の結果。
     * @param bool  $inside まとめリストの中かどうか。
     * @return string[]
     */
    function curation_tools_collect_matome_titles( $blocks, $inside = false ) {
    	$titles = array();
    	foreach ( $blocks as $block ) {
    		$class_names = isset( $block['attrs']['className'] ) ? explode( ' ', $block['attrs']['className'] ) : array();
    		$is_list     = 'core/group' === $block['blockName'] && in_array( 'curation-matome-list', $class_names, true );
    
    		if ( $inside && 'core/heading' === $block['blockName'] ) {
    			$text = curation_tools_plain_text( $block['innerHTML'] );
    			if ( '' !== $text ) {
    				$titles[] = $text;
    			}
    		}
    		if ( ! empty( $block['innerBlocks'] ) ) {
    			$titles = array_merge( $titles, curation_tools_collect_matome_titles( $block['innerBlocks'], $inside || $is_list ) );
    		}
    	}
    	return $titles;
    }
    
    /**
     * 記事ページの構造化データ(@graph の配列)を組み立てる。
     *
     * @param WP_Post $post 投稿。
     * @return array
     */
    function curation_tools_build_schema( WP_Post $post ) {
    	$permalink = get_permalink( $post );
    	$author    = get_userdata( (int) $post->post_author );
    
    	$article = array(
    		'@type'            => 'Article',
    		'@id'              => $permalink . '#article',
    		'mainEntityOfPage' => $permalink,
    		'headline'         => curation_tools_plain_text( get_the_title( $post ) ),
    		'datePublished'    => get_the_date( DATE_W3C, $post ),
    		'dateModified'     => get_the_modified_date( DATE_W3C, $post ),
    	);
    
    	if ( $author ) {
    		$person      = array(
    			'@type' => 'Person',
    			'name'  => $author->display_name,
    			'url'   => get_author_posts_url( $author->ID ),
    		);
    		$profile_url = (string) get_user_meta( $author->ID, 'curation_profile_url', true );
    		if ( '' !== $profile_url ) {
    			$person['sameAs'] = array( $profile_url );
    		}
    		$article['author'] = $person;
    	}
    
    	if ( has_post_thumbnail( $post ) ) {
    		$image = wp_get_attachment_image_url( get_post_thumbnail_id( $post ), 'full' );
    		if ( $image ) {
    			$article['image'] = array( $image );
    		}
    	}
    
    	$breadcrumb = array(
    		'@type'           => 'BreadcrumbList',
    		'itemListElement' => array(),
    	);
    	foreach ( curation_tools_get_breadcrumb_items( $post->ID ) as $index => $item ) {
    		$breadcrumb['itemListElement'][] = array(
    			'@type'    => 'ListItem',
    			'position' => $index + 1,
    			'name'     => $item['name'],
    			'item'     => $item['url'],
    		);
    	}
    
    	$graph = array( $article, $breadcrumb );
    
    	// まとめ/ランキング記事は、まとめリストの項目を ItemList として出す(項目が2つ以上のとき)。
    	$template = get_page_template_slug( $post );
    	if ( in_array( $template, array( 'single-matome', 'single-ranking' ), true ) ) {
    		$titles = curation_tools_collect_matome_titles( parse_blocks( $post->post_content ) );
    		if ( count( $titles ) >= 2 ) {
    			$list = array(
    				'@type'           => 'ItemList',
    				'name'            => $article['headline'],
    				'itemListOrder'   => 'https://schema.org/ItemListOrderAscending',
    				'numberOfItems'   => count( $titles ),
    				'itemListElement' => array(),
    			);
    			foreach ( $titles as $index => $title ) {
    				$list['itemListElement'][] = array(
    					'@type'    => 'ListItem',
    					'position' => $index + 1,
    					'name'     => $title,
    				);
    			}
    			$graph[] = $list;
    		}
    	}
    
    	/**
    	 * 構造化データを追加・変更するためのフィルター。
    	 *
    	 * @param array   $graph @graph に入れる配列。
    	 * @param WP_Post $post  投稿。
    	 */
    	return apply_filters( 'curation_tools_schema_graph', $graph, $post );
    }
    
    /**
     * 記事ページの <head> に JSON-LD を出力する。
     *
     * 文字列の連結で JSON を組み立てず、配列を wp_json_encode() で変換する。
     * JSON_HEX_TAG で < と > を \u003C / \u003E に変換し、記事タイトルなどに
     * 「</script>」が含まれていてもスクリプトタグが途中で閉じないようにする。
     */
    function curation_tools_print_schema() {
    	if ( ! is_singular( 'post' ) ) {
    		return;
    	}
    	$post = get_queried_object();
    	if ( ! $post instanceof WP_Post || post_password_required( $post ) ) {
    		return;
    	}
    
    	$data = array(
    		'@context' => 'https://schema.org',
    		'@graph'   => curation_tools_build_schema( $post ),
    	);
    	$json = wp_json_encode( $data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP );
    	if ( false === $json ) {
    		return;
    	}
    
    	wp_print_inline_script_tag( $json, array( 'type' => 'application/ld+json' ) );
    }
    add_action( 'wp_head', 'curation_tools_print_schema' );

    画面に表示するパンくずリストのブロックです。項目は JSON-LD と同じ curation_tools_get_breadcrumb_items() から作ります。

    wp-content/plugins/curation-tools/blocks/breadcrumb/block.json(新規・全文)

    {
    	"$schema": "https://schemas.wp.org/wp/6.8/block.json",
    	"apiVersion": 3,
    	"name": "curation-tools/breadcrumb",
    	"version": "0.8.0",
    	"title": "パンくずリスト",
    	"category": "theme",
    	"icon": "arrow-right-alt2",
    	"description": "ホーム → カテゴリ → 記事の順に、記事の位置を表示する。構造化データ(BreadcrumbList)と同じ内容を出す。記事テンプレートに置いて使う。",
    	"keywords": [ "パンくず", "breadcrumb" ],
    	"textdomain": "curation-tools",
    	"supports": {
    		"html": false,
    		"reusable": false,
    		"spacing": {
    			"margin": true
    		}
    	},
    	"editorScript": "file:./index.js",
    	"style": "file:./style-index.css",
    	"render": "file:./render.php"
    }

    wp-content/plugins/curation-tools/blocks/breadcrumb/index.js(新規・全文)

    /**
     * パンくずリスト: ブロックの登録(エディター用)。表示は render.php で行う。
     */
    import { registerBlockType } from '@wordpress/blocks';
    import { useBlockProps } from '@wordpress/block-editor';
    
    import metadata from './block.json';
    import './style.css';
    
    function Edit() {
    	return (
    		<nav { ...useBlockProps() } aria-label="パンくずリスト">
    			<ol>
    				<li>ホーム</li>
    				<li>カテゴリ</li>
    				<li aria-current="page">記事のタイトル</li>
    			</ol>
    		</nav>
    	);
    }
    
    registerBlockType( metadata.name, {
    	edit: Edit,
    } );

    wp-content/plugins/curation-tools/blocks/breadcrumb/render.php(新規・全文)

    <?php
    /**
     * パンくずリスト: 公開ページの表示(動的ブロック)。記事ページ以外では何も出力しない。
     *
     * 項目は includes/schema.php の curation_tools_get_breadcrumb_items() から取り、
     * 構造化データ(BreadcrumbList)と画面の表示を同じ内容にする。
     *
     * @package Curation_Tools
     */
    
    if ( ! defined( 'ABSPATH' ) ) {
    	exit;
    }
    
    if ( ! is_singular( 'post' ) ) {
    	return;
    }
    
    $curation_items = curation_tools_get_breadcrumb_items( get_queried_object_id() );
    $curation_last  = count( $curation_items ) - 1;
    ?>
    <nav <?php echo get_block_wrapper_attributes(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?> aria-label="パンくずリスト">
    	<ol>
    		<?php foreach ( $curation_items as $curation_index => $curation_item ) : ?>
    			<?php if ( $curation_index === $curation_last ) : ?>
    				<li aria-current="page"><?php echo esc_html( $curation_item['name'] ); ?></li>
    			<?php else : ?>
    				<li><a href="<?php echo esc_url( $curation_item['url'] ); ?>"><?php echo esc_html( $curation_item['name'] ); ?></a></li>
    			<?php endif; ?>
    		<?php endforeach; ?>
    	</ol>
    </nav>

    wp-content/plugins/curation-tools/blocks/breadcrumb/style.css(新規・全文)

    /* パンくずリスト(フロントとエディターの両方に読み込まれる) */
    .wp-block-curation-tools-breadcrumb {
    	font-size: var(--wp--preset--font-size--small, 0.875rem);
    	color: var(--wp--preset--color--accent-4, #5f6670);
    }
    
    .wp-block-curation-tools-breadcrumb ol {
    	display: flex;
    	flex-wrap: wrap;
    	margin: 0;
    	padding: 0;
    	list-style: none;
    }
    
    .wp-block-curation-tools-breadcrumb li + li::before {
    	content: "/";
    	margin-inline: 0.5em;
    }

    プラグイン本体で、2つのファイルの読み込みと2つのブロックの登録を足します。wp-content/plugins/curation-tools/curation-tools.php に次の変更を加えます(+ が追加、- が削除)。

    --- a/wp-content/plugins/curation-tools/curation-tools.php
    +++ b/wp-content/plugins/curation-tools/curation-tools.php
    @@ -2,7 +2,7 @@
     /**
      * Plugin Name:       Curation Tools
      * Description:       キュレーションメディア用の小さな機能群(引用元カード・ランキング・関連記事・構造化データなど)。連載の各回で機能を追加していく。
    - * Version:           0.7.0
    + * Version:           0.8.0
      * Requires at least: 6.8
      * Requires PHP:      8.2
      * Author:            third-hero
    @@ -17,7 +17,7 @@ if ( ! defined( 'ABSPATH' ) ) {
     	exit;
     }
     
    -define( 'CURATION_TOOLS_VERSION', '0.7.0' );
    +define( 'CURATION_TOOLS_VERSION', '0.8.0' );
     define( 'CURATION_TOOLS_FILE', __FILE__ );
     define( 'CURATION_TOOLS_DIR', plugin_dir_path( __FILE__ ) );
     define( 'CURATION_TOOLS_URL', plugin_dir_url( __FILE__ ) );
    @@ -31,6 +31,8 @@ require_once CURATION_TOOLS_DIR . 'includes/profile-fields.php';
     require_once CURATION_TOOLS_DIR . 'includes/meta.php';
     require_once CURATION_TOOLS_DIR . 'includes/ranking.php';
     require_once CURATION_TOOLS_DIR . 'includes/related.php';
    +require_once CURATION_TOOLS_DIR . 'includes/toc.php';
    +require_once CURATION_TOOLS_DIR . 'includes/schema.php';
     
     /**
      * ブロックを登録する。
    @@ -43,6 +45,8 @@ function curation_tools_register_blocks() {
     	register_block_type( CURATION_TOOLS_DIR . 'build/author-box' );
     	register_block_type( CURATION_TOOLS_DIR . 'build/ranking' );
     	register_block_type( CURATION_TOOLS_DIR . 'build/related' );
    +	register_block_type( CURATION_TOOLS_DIR . 'build/toc' );
    +	register_block_type( CURATION_TOOLS_DIR . 'build/breadcrumb' );
     }
     add_action( 'init', 'curation_tools_register_blocks' );
     

    3つの記事テンプレートの先頭(header の最初)にパンくずリストを置きます。

    wp-content/themes/curation-child/templates/single.html に次の変更を加えます(+ が追加、- が削除)。

    --- a/wp-content/themes/curation-child/templates/single.html
    +++ b/wp-content/themes/curation-child/templates/single.html
    @@ -4,6 +4,7 @@
     <main class="wp-block-group" style="margin-top:var(--wp--preset--spacing--60)">
     	<!-- wp:group {"tagName":"header","layout":{"type":"constrained"}} -->
     	<header class="wp-block-group">
    +		<!-- wp:curation-tools/breadcrumb {"style":{"spacing":{"margin":{"bottom":"var:preset|spacing|30"}}}} /-->
     		<!-- wp:template-part {"slug":"post-meta"} /-->
     		<!-- wp:post-title {"level":1} /-->
     		<!-- wp:post-featured-image {"aspectRatio":"16/9"} /-->

    wp-content/themes/curation-child/templates/single-matome.html に次の変更を加えます(+ が追加、- が削除)。

    --- a/wp-content/themes/curation-child/templates/single-matome.html
    +++ b/wp-content/themes/curation-child/templates/single-matome.html
    @@ -4,6 +4,7 @@
     <main class="wp-block-group" style="margin-top:var(--wp--preset--spacing--60)">
     	<!-- wp:group {"tagName":"header","layout":{"type":"constrained"}} -->
     	<header class="wp-block-group">
    +		<!-- wp:curation-tools/breadcrumb {"style":{"spacing":{"margin":{"bottom":"var:preset|spacing|30"}}}} /-->
     		<!-- wp:paragraph {"className":"curation-type-label","textColor":"brand","fontSize":"small"} -->
     		<p class="curation-type-label has-brand-color has-text-color has-small-font-size">まとめ</p>
     		<!-- /wp:paragraph -->

    wp-content/themes/curation-child/templates/single-ranking.html に次の変更を加えます(+ が追加、- が削除)。

    --- a/wp-content/themes/curation-child/templates/single-ranking.html
    +++ b/wp-content/themes/curation-child/templates/single-ranking.html
    @@ -4,6 +4,7 @@
     <main class="wp-block-group" style="margin-top:var(--wp--preset--spacing--60)">
     	<!-- wp:group {"tagName":"header","layout":{"type":"constrained"}} -->
     	<header class="wp-block-group">
    +		<!-- wp:curation-tools/breadcrumb {"style":{"spacing":{"margin":{"bottom":"var:preset|spacing|30"}}}} /-->
     		<!-- wp:paragraph {"className":"curation-type-label","textColor":"brand","fontSize":"small"} -->
     		<p class="curation-type-label has-brand-color has-text-color has-small-font-size">ランキング</p>
     		<!-- /wp:paragraph -->

    wp-content/themes/curation-child/style.css に次の変更を加えます(+ が追加、- が削除)。

    --- a/wp-content/themes/curation-child/style.css
    +++ b/wp-content/themes/curation-child/style.css
    @@ -4,7 +4,7 @@ Theme URI:         https://example.com/
     Description:       「WordPressでキュレーションメディアを作る」連載用の Twenty Twenty-Five 子テーマ。
     Author:            third-hero
     Template:          twentytwentyfive
    -Version:           0.7.0
    +Version:           0.8.0
     Requires at least: 6.8
     Tested up to:      6.8
     Requires PHP:      8.2

    動作確認の方法

    第0回・第2回の手順の後、プラグインをビルド(プラグインのフォルダで npm run build)してから確認しました(筆者の環境で確認済みです)。テスト用に、目次ブロック・h2/h3 の見出し・まとめリストを含む「まとめ」テンプレートの記事を作ります。本文は次のファイルを使います。

    テスト用の本文 toc-test.html(プロジェクトのフォルダに作る。確認が終わったら消してよい)

    <!-- wp:curation-tools/toc /-->
    
    <!-- wp:heading -->
    <h2 class="wp-block-heading">この記事で比べること</h2>
    <!-- /wp:heading -->
    
    <!-- wp:paragraph -->
    <p>目次と構造化データの確認用の本文です。</p>
    <!-- /wp:paragraph -->
    
    <!-- wp:group {"className":"curation-matome-list","layout":{"type":"default"}} -->
    <div class="wp-block-group curation-matome-list"><!-- wp:group {"className":"curation-matome-item","layout":{"type":"default"}} -->
    <div class="wp-block-group curation-matome-item"><!-- wp:heading {"level":3,"className":"curation-matome-item__title"} -->
    <h3 class="wp-block-heading curation-matome-item__title">公的機関のガイドライン</h3>
    <!-- /wp:heading --></div>
    <!-- /wp:group -->
    
    <!-- wp:group {"className":"curation-matome-item","layout":{"type":"default"}} -->
    <div class="wp-block-group curation-matome-item"><!-- wp:heading {"level":3,"className":"curation-matome-item__title"} -->
    <h3 class="wp-block-heading curation-matome-item__title">業界団体のチェックリスト</h3>
    <!-- /wp:heading --></div>
    <!-- /wp:group --></div>
    <!-- /wp:group -->
    
    <!-- wp:heading -->
    <h2 class="wp-block-heading">まとめ</h2>
    <!-- /wp:heading -->
    docker compose run --rm -T wpcli wp post create - --post_title=目次テスト --post_name=toc-test \
      --post_status=publish --post_author=1 --post_category=security --page_template=single-matome < toc-test.html

    作った記事(toc-test)で確認します。

    # JSON-LD を取り出して、JSON として正しいか確認する
    curl -s http://localhost:8088/toc-test/ \
      | sed -n '/application\/ld+json/,/<\/script>/p' | sed '1d;$d' \
      | python3 -m json.tool

    wp_print_inline_script_tag() は <script> タグと JSON の間で改行するため、1行で抜き出すのではなく、開始タグから終了タグまでの行を取り出しています。

    • JSON-LD が python3 -m json.tool で正しく読み込め、Article・BreadcrumbList・ItemList の3つが入っている
    • 著者の url(著者アーカイブ)と sameAs(プロフィール URL)、日付の +09:00、アイキャッチの画像 URL が入っている
    • タイトルに「</script>」の文字列を含む記事でも、JSON-LD の中では < と > がエスケープ表記に変換され、スクリプトタグが途中で閉じない
    • Schema Markup Validator(validator.schema.org)に JSON-LD を貼り付けて検証し、3種類ともエラー・警告が0件
    • 目次のリンクが見出しの id と一致し、ページ内の id に重複がない。ヘッドレスブラウザでリンクをクリックすると該当の見出しまで移動する
    • 見出しが1つだけの記事では、目次ブロックを置いても何も表示されない。一覧ページやフィードには目次・JSON-LD が出ない

    📰 出典:Schema Markup Validator

    Google のリッチリザルトテストは、ローカル環境の URL を読み込めないため今回は実施していません。公開環境で、URL またはコードを貼り付けて確認してください。

    つまずきやすい点・セキュリティ上の注意

    • 表示と構造化データのずれ:構造化データだけに情報を書き、画面に出さないのはガイドライン違反になり得ます。今回のように、表示と構造化データを同じ関数・同じ本文から作る設計にしておくと、ずれが起きにくくなります。
    • プラグインの重複:SEO 系のプラグインを後から入れると、同じ種類の構造化データが二重に出力されることがあります。導入前に、どの機能がどの構造化データを出しているかを確認してください。
    • 見出しの番号:第5回のまとめリストの「1.」「2.」は CSS で表示しているため、目次や ItemList の項目名には番号が入りません。目次は番号付きリスト(<ol>)で表示しているので、読者から見た順番は保たれます。
    • パスワード保護の記事:本文を見られない記事では、JSON-LD を出力しないようにしています。

    発注者向けメモ:構造化データは「正確さ」を保証する仕組みとして頼む

    構造化データは、正しく実装しても検索順位や特別な表示を保証するものではありません。発注の際は「リッチリザルトを出す」ではなく「ページの内容を正確に伝える構造化データを、表示とずれない仕組みで出す」ことを要件にしましょう。

    • 何を出すか:Article・パンくず・一覧など、どの種類を、どの種類のページに出すか
    • 何から作るか:画面の表示と同じデータ源から作っているか。手入力の項目がある場合、誰が更新するか
    • プラグインとの役割分担:SEO プラグインを使う場合、自作の構造化データと重複しないか
    • 確認方法:公開前にリッチリザルトテストや Schema Markup Validator で確認する工程を、受け入れテストに含めるか

    工数が増えるのは、商品・レビュー・イベントなど種類ごとに細かなルールがある構造化データを扱う場合や、複数のカテゴリ・複数の経路のパンくずを出し分ける場合です。

    打ち合わせでは、次のように聞いてみてください。

    • 「構造化データの内容は、画面に表示している内容とどうやって一致させていますか?」
    • 「タイトルに記号や </script> のような文字列が入っても、JSON-LD が壊れない作りになっていますか?」
    • 「リッチリザルトテストでの確認は、どの工程で誰が行いますか?」

    まとめと次回予告

    第8回では、目次と構造化データを作りました。

    • 目次は、本文の HTML が組み立て終わった後に見出しへの id 付与と目次の作成を同時に行い、ずれを防ぐ
    • パンくずは画面の表示と JSON-LD を同じ関数から作る
    • Article には画面に表示している著者・日付・画像を入れ、日付はタイムゾーン付きの形式にする
    • まとめ記事の ItemList は構造を正確に表すためのもので、Google のカルーセル表示の対象ではない
    • JSON-LD は wp_json_encode() と JSON_HEX_TAG で安全に出力する。リッチリザルトの表示は保証されない

    次回は「OGP・SNS カードと「広告・PR表記」― ステマ規制への対応」です。SNS で共有されたときのカード表示と、広告を含む記事の PR 表記を自動で入れる仕組みを作ります。

    この連載の記事一覧

    この記事は連載「WordPressで作るキュレーションメディア」の1回です。連載のほかの回は次のとおりです(連載の一覧ページ)。

    システム制作・運用・保守のお問い合わせはこちら

      お問い合わせ


      よかったらシェアしてね!
      • URLをコピーしました!
      • URLをコピーしました!

      この記事を書いた人

      株式会社THIRD HERO代表取締役 朝野貴朗
      Webシステム開発を中心に、toC向けサービスサイトの運営、ツール開発などを行ってまいりました。

      コメント

      コメント一覧 (1件)

      目次