[WordPress] プラグインなしで投稿・固定ページにnoindexが設定できる機能を実装する

投稿ページや固定ページを個別にnoindex設定をしたい場合に重宝します。この機能は、人気のプラグイン「All in One SEO Pack」などで実装することも可能ですが、多機能ということもあり、機能がダブってしまったりサイト全体が重くなってしまうデメリットもあります。そのため、今回はプラグインなしで実装する方法を紹介します。

カスタムフィールドを追加する

functions.php内にカスタムフィールドの設定していきます。

/**
 * カスタムフィールドの追加
 * noindex,nofollow設定
 */

// カスタムフィールドの設定
function theme_add_seo_fields() {
	$post_type = array( 'post', 'page' );

	add_meta_box( 'seo_setting', 'SEO設定', 'theme_insert_seo_fields', $post_type, 'normal');
}
add_action( 'admin_menu', 'theme_add_seo_fields' );

// カスタムフィールドの入力エリア設定
function theme_insert_seo_fields() {
	global $post;

	if( get_post_meta( $post->ID, 'check_noindex' , true ) == "is-on" ) {
		$check_noindex = 'checked';
	} else {
		$check_noindex = '';
	}
	echo 'noindex,nofollow設定: <input type="checkbox" name="check_noindex" value="is-on" ' . $check_noindex . ' ><br>';
}

// カスタムフィールドの値を保存
function theme_save_seo_fields( $post_id ) {

	if( !empty( $_POST['check_noindex'] ) ) {
		update_post_meta( $post_id, 'check_noindex', $_POST['check_noindex'] );
	}else{
		delete_post_meta( $post_id, 'check_noindex' );
	}
}
add_action('save_post', 'theme_save_seo_fields');

上記の設定をすることでWordPressの管理画面から確認することができます。確認できたら、出力側の設定を定義していきます。

管理画面にチェックボックス項目が表示されている

メタタグ挿入関数を定義する

同じくfunctions.php内に、メタタグを挿入する関数を定義します。

/**
 *
 * noindex,nofollow metaタグ追加
 */

function theme_display_noindex_meta() {
	global $post;
	if ( get_post_meta( $post->ID, 'check_noindex' ) ) {
		echo '<meta name="robots" content="noindex,nofollow">';
	}
}

メタタグを挿入する

WordPressテーマのheadタグ内に先ほど定義した関数を記述します。

<!DOCTYPE html>
<html lang="ja">
<head>
	<?php theme_display_noindex_meta(); ?>
</head>

おまけ

アーカイブページや404ページの場合も、クロールする必要がないのでnoindexタグを入れておきます。

/**
 *
 * noindex,nofollow metaタグ追加
 */

function theme_display_noindex_meta() {
	global $post;
	$metatag = '<meta name="robots" content="noindex,nofollow">';

	if ( get_post_meta( $post->ID, 'check_noindex' ) ) {
		echo $metatag;
	} elseif ( is_archive() || is_404() ) {
		echo $metatag;
	}
}

石井秀幸@WEBデザイナー
横浜WordPress Meetup 主宰/株式会社ノクチ基地 取締役/モンゼンクリエイティブ合同会社 代表
WEB制作に関する技術や役立つ情報を発信していきます。10年にわたるWordPress歴を背景に、幅広いアイデアを形にするお手伝いをしています。