【コピペで使える】プラグインを使わず投稿ページに独自のタイトル・キーワード・紹介文を追加~表示させるWordPressサンプルコード

WordPressサイトで投稿ページ毎に独自のタイトルやキーワード、紹介文を設定する場合、「All in One SEO」や「Yoast」といったプラグインを利用するのが一般的です。

ただこれらのプラグインは結構”重い”です。

実際クライアントのウェブサイトがこれらプラグイン導入後にタイムアウトが頻発するといったことがあったため、今回プラグインを一切使わずに独自実装をすることになりましたので、その際のコードをサンプルとして共有します。

SEO対策のために投稿ページには自由にタイトルやキーワード、紹介文を設定したい、でもそれだけのために重たいプラグインを導入するのは避けたい・・・そんな方は是非ご活用ください。

※見栄え等カスタマイズが必要な個所あれば各自調整をお願いいたします。
 

functions.php


<?php
// 入力欄作成
function insert_seo_fields() {
  global $post;
  echo '<p>タイトル<br /><input type="text" name="seo_title" value="' . get_post_meta($post->ID, 'seo_title', true) . '" size="100" /></p>';
  echo '<p>キーワード<br /><input type="text" name="seo_keywords" value="' . get_post_meta($post->ID, 'seo_keywords', true) . '" size="100" /></p>';
  echo '<p>紹介文<br /><textarea name="seo_description" cols="103" rows="8">' . get_post_meta($post->ID, 'seo_description', true) . '</textarea></p>';
}

// 投稿画面への入力欄表示
function add_seo_fields() {
  add_meta_box('seo_setting', 'SEO設定', 'insert_seo_fields', 'post', 'normal');
  add_meta_box('seo_setting', 'SEO設定', 'insert_seo_fields', 'page', 'normal');
}
add_action('admin_menu', 'add_seo_fields');

// 入力値の保存
function save_seo_fields($post_id) {
  if(!empty($_POST['seo_title'])) {
    update_post_meta($post_id, 'seo_title', $_POST['seo_title'] ); //値を保存
    update_post_meta($post_id, 'seo_keywords', $_POST['seo_keywords'] ); //値を保存
    update_post_meta($post_id, 'seo_description', $_POST['seo_description'] ); //値を保存
  } else{
    delete_post_meta($post_id, 'seo_title'); //値を削除
    delete_post_meta($post_id, 'seo_keywords'); //値を削除
    delete_post_meta($post_id, 'seo_description'); //値を削除
  }
}
add_action('save_post', 'save_seo_fields');

// タイトルの変更
function change_document_title(){
  if(is_single() || is_page()){
    $title = get_post_meta(get_the_ID(), 'seo_title', true);
  }
  return $title;
}
add_filter('pre_get_document_title', 'change_document_title');

// 紹介文とキーワードの追加
function change_meta_keywords_description(){
  if(is_single() || is_page()){
    $description = get_post_meta(get_the_ID(), 'seo_description', true);
    if (!empty($description)) {
      printf( '<meta name="description" content="%s" />' . "\n", str_replace(array("\r","\n"), '', $description) );
    }
    $keywords = get_post_meta(get_the_ID(), 'seo_keywords', true);
    if (!empty($keywords)) {
      printf( '<meta name="keywords" content="%s" />' . "\n", str_replace(array("\r","\n"), '', $keywords) );
    }
  }
}
add_action('wp_head', 'change_meta_keywords_description');
?>

Follow me!