JSON-LD(構造化データ)を出力する方法

[WordPress] JSON-LD(構造化データ)を出力する方法

※ 当サイトは広告を含みます。

WordPressでJSON-LD(構造化データ)を出力する方法です。

JSON-LDってのはGoogleも推奨してるWebページの情報をJSONで記述する手法です。
これでクローラーのHTML解析よりも正しい情報を伝えることができるらしい。
https://developers.google.com/search/docs/appearance/structured-data/intro-structured-data?hl=ja

管理人
管理人

つまりSEO的に有利ってこと。

りさ
りさ

そうなの?

管理人
管理人

知らん。Googleに聞いてくれ。

◆ 安全にfunctions.phpをカスタマイズする方法
functions.phpの修正に不安がある人は以下を参考にしてください。

コードを追加する

functions.phpとかに以下のコードを追加します。
著作情報とかは自分のサイトに合わせて変更してください。


// JSON-LD 出力
add_action('wp_head', function () {
  $home_url = esc_url(home_url('/'));

  $thumbnail = $home_url . 'thumbnail.webp';
  if (has_post_thumbnail()) {
    $thumbnail = get_the_post_thumbnail_url();
  }

  $post_time     = get_the_time('c');
  $modified_time = get_the_modified_time('c');

  $author = array(
    '@type'  => 'Person',
    'name'   => '著者の名前',
    'url'    => '著者のメインURL',
    'sameAs' => array(
      '著者のサブURL(SNSアカウント等)',
    ),
  );

  $logo = $home_url . 'favicon.ico';

  $json_ld = array();

  if (is_front_page()) {
    $json_ld['WebSite'] = array(
      '@context'        => 'https://schema.org',
      '@type'           => 'WebSite',
      'name'            => get_bloginfo('name'),
      'url'             => $home_url,
      'description'     => get_bloginfo('description'),
      'author'          => $author,
      'inLanguage'      => 'jp',
      'image'           => $logo,
      'potentialAction' => array(
        '@type'  => 'SearchAction',
        'target' => array(
          '@type'       => 'EntryPoint',
          'urlTemplate' => $home_url . '?s={search_term_string}',
        ),
        'query-input' => 'required name=search_term_string',
      ),
    );
  }

  if (is_singular()) {
    $json_ld['BlogPosting'] = array(
      '@context' => 'https://schema.org',
      '@type'    => 'BlogPosting',
      'headline' => get_the_title(),
      'image'    => array(
        $thumbnail,
      ),
      'datePublished' => $post_time,
      'dateModified'  => $modified_time > $post_time ? $modified_time : $post_time,
      'author'        => $author,
    );
  }

  foreach ($json_ld as $obj) {
    echo '<script type="application/ld+json">' . json_encode($obj, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT) . '</script>';
  }
}, 1);

仕組み

単にwp_headで出力するJSON-LDを書いてるだけ。
if文はページの種類で出力をコントロールするためにあります。

あとがき

確かにクローラーが理解しやすいってのはSEO的に有利と思えなくもない。

この記事は参考になりましたか?

関連記事

コメント

この記事へのコメントはありません。