プラグインなし!SEO施策機能を導入する方法。|WordPress

WordPressで、プラグインを使わずに施策機能を導入する方法をご紹介致します。

プラグイン不使用には、サーバー負荷の軽減やサイト表示速度の保持など様々なメリットがあります。

WordPressには多種多様なプラグインがたくさんあり、SEO対策では、「All in One SEO Pack」や「Yoast SEO」など優秀なプラグインがあります。

しかしSEO対策のプラグインは特に重いです。

コンテンツを充実させ検索エンジン上位を目指しているのに、表示速度が遅くて離脱されてしまったら本末転倒です。

ですので、今回は「軽い」「早い」「設置が簡単」な実装方法をご紹介致します。

functions.phpの編集

functions.phpにコードコピペ

functions.phpの編集を行います。

子テーマが利用できる環境であれば子テーマのfunctions.phpを利用してください。

各コードの説明書きはそれぞれ記載していますので、参考にされてください。

※必ずバックアップをとってから編集してください。

//SEOカスタムフィールドの設定
class Custom_Field_4536 {
    function __construct() {
        add_filter( 'document_title_parts', [ $this, 'title_update' ] );
        if(!is_admin()) return;
        add_action( 'add_meta_boxes', [ $this, 'init' ] );
        add_action( 'transition_post_status', [ $this, 'save' ], 10, 3 );
	}
    function init() {
        $list = [
            'SEO対策' => 'seo_custom_fields',
        ];
        $args = [
            'public'   => true,
            '_builtin' => false,
        ];
        $post_types = get_post_types( $args, 'names' );
        foreach($list as $title => $id) {
            add_meta_box( $id, $title, $id, 'post', 'normal', 'high');
            add_meta_box( $id, $title, $id, 'page', 'normal', 'high');
            foreach ( $post_types as $post_type ) {
                add_meta_box( $id, $title, $id, $post_type, 'normal', 'high');
            }
        }
    }
    function save($new_status, $old_status, $post) {
        if (($old_status == 'auto-draft'
        || $old_status == 'draft'
        || $old_status == 'pending'
        || $old_status == 'future')
        && $new_status == 'publish') {
            return $post;
        } else {
            add_action('save_post', function($post_id) {
                $list = [
                    'keywords',
                    'description',
                    'noindex',
                    'nofollow',
                    'sns_title',
                    'seo_title',
                ];
                foreach($list as $name) {
                    if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return $post_id;
                    if(isset($_POST['action']) && $_POST['action'] == 'inline-save') return $post_id;
                    if(!empty($_POST[$name]))
                    update_post_meta($post_id, $name, $_POST[$name] );
                    else delete_post_meta($post_id, $name);
                }
            });
        }
    }
    function title_update($title) {
        global $post;
        $seo_title = get_post_meta($post->ID,'seo_title',true);
        if(is_singular() && $seo_title) $title['title'] = $seo_title;
        return $title;
    }
}
new Custom_Field_4536();
// 設定項目の作成
function seo_custom_fields() {
    global $post;
    $list = [
        'seo_title' => 'SEO用タイトル(タイトルタグ書き換え)',
        'sns_title' => 'SNS用タイトル',
    ];
    foreach($list as $name => $description) { ?>
        <div class="input-wrapper-4536">
            <div id="<?php echo $name; ?>-counter" class="counter"></div>
            <label for="<?php echo $name; ?>" class="label-4536"><?php echo $description; ?></label>
            <input name="<?php echo $name; ?>" id="<?php echo $name; ?>" value="<?php echo esc_html(get_post_meta($post->ID, $name, true)); ?>" size="60" class="input-4536" type="text" />
            <div style="clear:both;"></div>
        </div>
    <?php } ?>
    <div class="input-wrapper-4536">
        <div id="description-counter" class="counter"></div>
        <label for="description" class="label-4536">ページの説明(推奨:160文字ほど)※何も入力しない場合、先頭の文字が自動で使われます。</label>
        <textarea name="description" id="description" cols="60" rows="6" class="input-4536"><?php echo esc_html(get_post_meta($post->ID, 'description', true)); ?></textarea>
        <div style="clear:both;"></div>
    </div>
    <?php $list = [
        'keywords' => 'キーワード(コンマ区切り)',
    ];
    foreach($list as $name => $description) { ?>
        <div class="input-wrapper-4536">
            <label for="<?php echo $name; ?>" class="label-4536"><?php echo $description; ?></label>
            <input name="<?php echo $name; ?>" id="<?php echo $name; ?>" value="<?php echo esc_html(get_post_meta($post->ID, $name, true)); ?>" size="60" class="input-4536" type="text" />
            <div style="clear:both;"></div>
        </div>
    <?php }
    $list = [
        'noindex' => 'NOINDEX(検索結果への表示をブロックします)',
        'nofollow' => 'NOFOLLOW(リンクを除外します)ほとんどの場合、チェックを入れる必要はありません。',
    ];
    foreach($list as $name => $description) {
        $check = (get_post_meta($post->ID, $name ,true) == 1) ? 'checked' : '/' ; ?>
        <div class="input-wrapper-4536">
            <label for="<?php echo $name; ?>" class="label-4536"><?php echo $description; ?></label>
            <span class="checkbox-4536">
                <input type="checkbox" name="<?php echo $name; ?>" id="<?php echo $name; ?>" value="1" <?php echo $check; ?> >
            </span>
            <div style="clear:both;"></div>
        </div>
    <?php } ?>
    <style>
        .input-wrapper-4536 {
            margin: 20px 0;
            position: relative;
        }
        .label-4536 {
            float: left;
            margin: 0;
            width: 37%;
            padding: 3px 30px 3px 0;
            -webkit-box-sizing: border-box;
            box-sizing: border-box;
        }
        .input-4536 {
            float: left;
            width: 63%;
            margin: 0;
        }
        .checkbox-4536 {
            float: left;
            margin-top: 3px;
        }
        .counter {
            text-align: right;
            width: 100%;
        }
        .title-counter-length-over {
            color: #f00;
            font-weight: bold;
        }
    </style>
<?php }
// 設定の反映
add_action( 'wp_head', function() {
    global $post;
    $keywords = get_post_meta($post->ID,'keywords',true);
    $noindex = get_post_meta($post->ID,'noindex',true);
    $nofollow = get_post_meta($post->ID,'nofollow',true);
    $robots = '';
    if($noindex && $nofollow) $robots = '<meta name="robots" content="noindex,nofollow">';
    if($noindex && !$nofollow) $robots = '<meta name="robots" content="noindex,follow">';
    if(!$noindex && $nofollow) $robots = '<meta name="robots" content="nofollow">';
    if(description_4536()) echo '<meta name="description" content="'.description_4536().'">';
    if(is_singular()) { //記事ページ
        echo $robots;
        if($keywords) echo '<meta name="keywords" content="'.$keywords.'">';
    }
});
// 文字数カウンター
function text_counter_4536() { ?>
<script type="text/javascript">
    var list = [
        '#seo_title',
        '#description',
        '#sns_title'
    ];
    $(function() {
        $.each(list, function(index,value) {
            function counter_4536() {
                var length = $(value).val().length;
                $(value + '-counter').html(length);            
            }
            counter_4536();
            $(value).on('keydown keyup keypress change', counter_4536);
        });
    });
</script>
<?php }
add_action( 'admin_head-post.php', 'text_counter_4536' );
add_action( 'admin_head-post-new.php', 'text_counter_4536' );

//ディスクリプション設定
function description_4536() {
    if(is_home()) {
        $description = get_bloginfo('description') ;
    } elseif(is_singular() || is_front_page()) { // 記事ページ
        //カスタムフィールドで設定したディスクリプション
        $custom_description = get_post_meta(get_the_ID(), 'description', true);
        $custom_description = strip_tags(str_replace(array("\r\n", "\r", "\n"), '', $custom_description));
        $custom_description = mb_strimwidth($custom_description, 0, 320, "...", "utf-8");
        $auto_description = get_post(get_the_ID())->post_content;
        $auto_description = strip_tags(str_replace(array("\r\n", "\r", "\n"), '', $auto_description));
        $auto_description = mb_strimwidth($auto_description, 0, 320, "...", "utf-8");
        //条件によって読み込むディスクリプションを変更
        $post_description = ($custom_description) ? $custom_description : $auto_description ;        
        $description = $post_description;
    } elseif(is_category()) { // カテゴリーページ
        if(term_description()) { //カテゴリーの説明を入力している場合
            $description = term_description();
        } else { //カテゴリーの説明がない場合
            $description = single_cat_title('', false).'の記事一覧';
        }
    } elseif(is_tag()) { // タグページ
        if(term_description()) { //タグの説明を入力している場合
            $description = term_description();
        } else { //タグの説明がない場合
            $description = single_tag_title('', false).'の記事一覧';
        }
    } elseif(is_day()) {
         $description = get_the_time('Y年m月d日').'の記事一覧';
    } elseif(is_month()) {
        $description = get_the_time('Y年m月').'の記事一覧';
    } elseif(is_year()) {
        $description = get_the_time('Y年').'の記事一覧';
    } elseif(is_author()) {
        $description = get_queried_object()->display_name.'の記事一覧';
    }
    if($description) return esc_html($description);
}
// ユーザー設定に項目を追加
add_filter('user_contactmethods', function($sns) {
	$sns['twitter'] = 'Twitter(twitter.com/以降)';
	$sns['fb_app_id'] = 'FacebookアプリID';
	return $sns;
});

// OGPタグ/Twitterカード設定を出力
function my_meta_ogp() {
  if( is_front_page() || is_home() || is_singular() ){
    global $post;
    $ogp_title = '';
    $ogp_descr = '';
    $ogp_url = '';
    $ogp_img = '';
    $insert = '';

    if( is_singular() ) { //記事&固定ページ
       setup_postdata($post);
       $ogp_title = $post->post_title;
       $ogp_descr = mb_substr(get_the_excerpt(), 0, 100);
       $ogp_url = get_permalink();
       wp_reset_postdata();
    } elseif ( is_front_page() || is_home() ) { //トップページ
       $ogp_title = get_bloginfo('name');
       $ogp_descr = get_bloginfo('description');
       $ogp_url = home_url();
    }

    //og:type
    $ogp_type = ( is_front_page() || is_home() ) ? 'website' : 'article';

    //og:image
    if ( is_singular() && has_post_thumbnail() ) {
       $ps_thumb = wp_get_attachment_image_src( get_post_thumbnail_id(), 'full');
       $ogp_img = $ps_thumb[0];
    } else {
     $ogp_img = 'https://blog.gunjow.net/wp-content/uploads/frecer_og.png';
    }

    //出力するOGPタグをまとめる
    $insert .= '<meta property="og:title" content="'.esc_attr($ogp_title).'" />' . "\n";
    $insert .= '<meta property="og:description" content="'.esc_attr($ogp_descr).'" />' . "\n";
    $insert .= '<meta property="og:type" content="'.$ogp_type.'" />' . "\n";
    $insert .= '<meta property="og:url" content="'.esc_url($ogp_url).'" />' . "\n";
    $insert .= '<meta property="og:image" content="'.esc_url($ogp_img).'" />' . "\n";
    $insert .= '<meta property="og:site_name" content="'.esc_attr(get_bloginfo('name')).'" />' . "\n";
    $insert .= '<meta name="twitter:card" content="summary_large_image" />' . "\n";
    $insert .= '<meta name="twitter:site" content="frecer" />' . "\n";
    $insert .= '<meta property="og:locale" content="ja_JP" />' . "\n";

    //facebookのapp_id(設定する場合)
    $insert .= '<meta property="fb:app_id" content="226024900000000">' . "\n";
    //app_idを設定しない場合ここまで消す

    echo $insert;
  }
} //END my_meta_ogp

add_action('wp_head','my_meta_ogp');//headにOGPを出力

デフォルト画像の設定

252行目

個別ページにアイキャッチ画像を設定していない場合に、ここで指定した画像が表示されます。

任意のものに変更してください。

Twitter設定

262行目

サイトに関連したTwitterアカウントがありましたら@マーク以降を任意のものに変更してください。

Facebook設定

267行目

FacebookのアプリIDを取得し、任意のものに変更してください。

トップページ表示設定

WordPress管理画面の「設定 > 一般」に移動し、サイトのタイトルとキャッチフレーズを入力してください。

ここで入力させたものが、検索エンジンで表示されます。

個別ページ表示設定

固定ページや投稿ページなど個別にSEO設定する場合は、個別ページ下部にボックスが設置されていますので、それぞれ必要箇所に入力してください。

まとめ

今回はプラグインを使わずにWordPressに「SEO施策機能を実装する方法」をご紹介しました。

作業自体は時間もかからず、すぐに実装できますので宜しければ参考にされてください。

最後までご覧いただきありがとうございました。

Web
Web

Webです。Webサイト・ホームページ制作を行っております。また、WordpressテーマやWordpressプラグイン、画像や動画などのデジタル商品販売も行っております。格安提供させておりますので是非お立ち寄りください。 https://web.gunjow.net

コメント・評価ご感想をお待ちしております

コメント・評価

GUNJOW BLOG
Logo
新規会員登録