SNSなどでシェアされるときにサムネイル画像やタイトルを表示させる設定、OGP(Open Graph protocol)の設定を引き続きやっていきましょう。今回はTwitterです。
前回の記事
OGPってなんぞや?導入方法を一度試してみたいという方は導入編をご覧ください。

Twitter(Twitter Card)への設定
前回はFacebookに対する設定を行いました。次はTwitterの設定です。写真や動画などのリッチメディアをツイートに添付する機能をTwitterカードと呼んでいます。
※詳細:Twitterカード | Twitter Developers
追加するmeta要素はこちら。
Twitterカード用設定に必要な追加する<meta>要素
twitter:card – 写真や動画などのリッチメディアをツイートに添付する内容を指定。
twitter:site – サイトのTwitterアカウント、もしくはページの管理者のTwitterアカウント。
Twitterカードはさまざまな種類がありますが、タイトル、説明、サムネイル、Twitterアカウントの属性が含まれる”summaryカード”にしました。
function.phpを修正する
前回作成したmeta要素の関数function.phpにあるので、修正します。
ogp_meta()関数の画像のURL、取得したアプリケーションID、FacebookページのURL、Twitterアカウントは自分のサイトに合わせて変更してください。
function.phpを修正するので、バックアップを忘れずに!
//meta要素の設定
function ogp_meta() {
//管理パネルでなければOGPを付ける
if (!is_admin()) {
global $post;
$format = '<meta property="%1$s" content="%2$s">';
$type = 'website';
$url = esc_url(home_url('/'));
$site_name = esc_attr(get_option('blogname'));
$title = $site_name;
$image = home_url().'画像のURL';
$description = esc_attr(get_option('blogdescription'));
$app_id = '取得したアプリケーションID';
$publisher = 'Facebookページ';
$twitter_card= 'summary';
$twitter_site='Twitterアカウント';
//記事ページの場合
if (is_singular()) {
$type = 'article';
$url = esc_url(get_permalink($post->ID));
$title = esc_attr($post->post_title);
$description = strip_tags($post->post_excerpt ? $post->post_excerpt : $post->post_content);
$description = mb_substr($description, 0, 90) . '...';
//サムネイルがあるかチェック
if (function_exists('has_post_thumbnail') AND has_post_thumbnail($post->ID)) {
$attachment = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'full');
$image = esc_url($attachment[0]);
} elseif (preg_match('/<img\s[^>]*src=["\']?([^>"\']+)/i', $post->post_content, $match)) {
$image = esc_url($match[1]);
}
}
$args = array(
'og:type' => $type,
'og:url' => $url,
'og:title' => $title,
'og:image' => $image,
'og:site_name' => $site_name,
'og:description' => $description,
'fb:app_id' => $app_id,
'article:publisher' => $publisher,
'twitter:card' => $twitter_card,
'twitter:site' => $twitter_site
);
foreach ($args as $key => $value) {
printf($format, $key, $value);
}
}
}
add_action('wp_head', 'ogp_meta');
Twitter-Cardを申請する
英語で書かれた申請画面ですが、すんなりすることができました。詳しい申請画面を見たい方は以下のリンクへ。
動作確認
Twitterはこちらで確認することができます。
Card Validator | Twitter Developers
これで、設定完了です!おつかれさまでした!
まとめ
OGPが設定されて、私のブログもシェアされるとちゃんとサムネイルが表示されるようになってとてもうれしいですね。読んだ方のお役に立てればうれしいです。
参考にさせていただいたサイト
自分のブログに導入するにあたり、参考にさせていただきました。ありがとうございます!

