WordPressでAuthorの構造化データを出力する実装サンプル

WordPressで記事の執筆者ユーザー情報を取得して、構造化データ(Author)として出力する実装サンプルです。

①Advance Custom Fieldに執筆者情報を追加

プラグイン「Advanced Custom Fields」をインストール後、上図のようにユーザータイプの執筆者項目を投稿に対して設定します。

②functions.phpにアクションフックを追加

function my_meta_ogp()
{

global $post;

$title = "";
$description = "";
$url = "";
$html = "";

$title = get_bloginfo('name');
$description = "デフォルトの紹介文";
$url = home_url();

if (is_single() || is_page()) {

  setup_postdata($post);

  $title = $post->post_title;
  $description = strip_shortcodes($post->post_content);
  $description = wp_html_excerpt($description, 100, '…');
  $url = get_permalink();

  $writerId = get_field('writer', $post->id);
  $writerInfo = get_userdata($writerId);
  $writerAvatar = get_avatar_data($writerId);
  $writer_first_name = $writerInfo->first_name;
  $writer_last_name = $writerInfo->last_name;
  $writer_description = $writerInfo->description;
  $writer_url = $writerInfo->url;
  $writer_image_url = $writerAvatar["url"];

  if(!empty($writerInfo)):

    $html .= '<script type="application/ld+json">';
    $html .= '{';
    $html .= '"@context": "https://schema.org",';
    $html .= '"@type": "Article",';
    $html .= '"mainEntityOfPage": "' . esc_url($url) . '",';
    $html .= '"headline": "' . esc_attr($title) . '",';
    $html .= '"description": "' . $description . '",';
    $html .= '"author": [{';
    $html .= '"@type": "Person",';
    $html .= '"name": "' . $writer_last_name . ' ' . $writer_first_name . '",';
    $html .= '"url": "' . $writer_url . '",';
    $html .= '}]';
    $html .= '}';
    $html .= '</script>';

    endif;
    wp_reset_postdata();

  }

  echo $html;

}
add_action('wp_head', 'my_meta_ogp');