LoginSignup
0
0

WordPressでページごとにインデックスの設定をする

Last updated at Posted at 2024-04-13

ページごとに任意でインデックスの設定をできるようにする方法です。
元のコードは以下のサイトです。header.phpが複数あった場合に、1つ1つに記述しなくてもいいよう、functions.phpにまとめる形で変更しました。元のコード + 一番下の関数を追加すれば、OK。

// 元コード
function add_noindex_metabox() {
    add_meta_box( 'custom_noindex', 'インデックス設定', 'create_noindex', array('post', 'page'), 'side' );
}
add_action('admin_menu', 'add_noindex_metabox');

function create_noindex() {
    $keyname = 'noindex';
    global $post;
    $get_value = get_post_meta($post->ID, $keyname, true);
    wp_nonce_field('action_' . $keyname, 'nonce_' . $keyname);
    $value = 'noindex';
    $checked = '';
    if ($value === $get_value) $checked = ' checked';
    echo '<label><input type="checkbox" name="' . $keyname . '" value="' . $value . '"' . $checked . '>' . $keyname . '</label>';
}

function save_custom_noindex($post_id) {
    $keyname = 'noindex';
    if (isset($_POST['nonce_' . $keyname])) {
        if (check_admin_referer('action_' . $keyname, 'nonce_' . $keyname)) {
            if (isset($_POST[$keyname])) {
                update_post_meta($post_id, $keyname, $_POST[$keyname]);
            } else {
                delete_post_meta($post_id, $keyname, get_post_meta($post_id, $keyname, true));
            }
        }
    }
}
add_action('save_post', 'save_custom_noindex');

// 追加するコード↓
function add_tag() {
    global $post;

    if (is_singular() && get_post_meta($post->ID, 'noindex', true)) {
        echo '<meta name="robots" content="noindex, nofollow" />';
    }
}
add_action('wp_head', 'add_tag');

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0