WordPressサイトのSNS対策を考える上で、OGP設定はとても重要な要素です。そしてこういった重要な要素はなるべくプラグインに依存したくないものです。
プラグインはアップデートでの不具合の発生やサポート切れなど様々な不安要素があり、そうなったときに機能しなくなるなどは避けたいですよね。
そこで今回はfunctions.phpへの記述でOGPの悩みを解決する、おすすめの記述方法をご紹介します。
functions.php内に下記をコピペして必要な箇所を記入いただければ完了です。
尚、functions.phpの編集はサイト全体に影響を及ぼしますので、必ずもとのファイルを保管して、問題が起きた際には戻せる状態にして進めてください。
function ogp_setting()
{
// SNS設定(記入してください)
$twitter_site = '@';
$twitter_card = 'summary_large_image';
$facebook_app_id = '';
// デフォルト設定(記入してください)
global $post;
$ogp_title = get_bloginfo('name');
$ogp_image = '';
$ogp_description = '';
$ogp_url = home_url();
$ogp_type = (is_front_page() || is_home()) ? 'website' : 'article';
$html = '';
// 投稿ページ・固定ページの場合
if (is_single() || is_page()) {
setup_postdata($post);
$ogp_title = $post->post_title;
$ogp_description = strip_shortcodes($post->post_content);
$ogp_description = wp_html_excerpt($ogp_description, 100, '…');
$ogp_description = $ogp_description;
$ogp_url = get_permalink();
wp_reset_postdata();
}
// アーカイブページの場合
if (is_archive()) {
$cat = get_the_category();
$cat = $cat[0];
$ogp_title = $cat->name;
$ogp_description = $cat->category_description;
$ogp_description = $ogp_description;
$ogp_url = "https://".$_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"];
}
// アイキャッチ画像設定
if ((is_single() || is_page()) && has_post_thumbnail()) {
$ps_thumb = wp_get_attachment_image_src(get_post_thumbnail_id(), 'full');
$ogp_image = $ps_thumb[0];
}
// HTML出力
$html = "\n";
$html .= '<meta name="description" content="' . $ogp_description . '">' . "\n";
$html .= '<meta property="og:title" content="' . esc_attr($ogp_title) . '">' . "\n";
$html .= '<meta property="og:description" content="' . $ogp_description . '">' . "\n";
$html .= '<meta property="og:type" content="' . $ogp_type . '">' . "\n";
$html .= '<meta property="og:url" content="' . esc_url($ogp_url) . '">' . "\n";
$html .= '<meta property="og:image" content="' . esc_url($ogp_image) . '">' . "\n";
$html .= '<meta property="og:site_name" content="' . esc_attr(get_bloginfo('name')) . '">' . "\n";
$html .= '<meta name="twitter:card" content="' . $twitter_card . '">' . "\n";
$html .= '<meta name="twitter:site" content="' . $twitter_site . '">' . "\n";
$html .= '<meta property="og:locale" content="ja_JP">' . "\n";
if ($facebook_app_id != "") {
$html .= '<meta property="fb:app_id" content="' . $facebook_app_id . '">' . "\n";
}
echo $html;
}
add_action('wp_head', 'ogp_setting');