ワードプレスのwp_robotsフィルタの使用方法・解説

概要

wp_robotsフィルタは、WordPressのページに関連するrobotsメタ要素を出力するために使用されます。このフィルタは、以下のような機能を実装する際によく使われます。

  1. 検索エンジンのクロールを制御するための設定
  2. 特定のページや投稿をインデックスから除外する
  3. 特定のページにのみクロールを許可または禁止する
  4. デフォルトのrobotsメタ設定を変更する
  5. カスタム投稿タイプのrobotsメタを追加する
  6. 固定ページと投稿の挙動を個別に設定する
  7. サイト全体のSEO設定を簡素化する
  8. プラグインの特定の機能を有効化または無効化する

構文

apply_filters( 'wp_robots', $robots, $post );

パラメータ

  • $robots (array): robotsメタ要素で出力される設定の配列
  • $post (WP_Post): 現在処理中の投稿オブジェクト

戻り値

  • array: 変更後のrobotsメタ設定の配列

関連する関数

wp_robots

使用可能なバージョン

このフィルタは、WordPress 4.4以降で利用可能です。

コアファイルのパス

wp-includes/general-template.php

この関数のアクションでの使用可能性

アクション 使用可能性
mu_plugin_loaded
registered_post_type
plugins_loaded
wp_roles_init
setup_theme
after_setup_theme
set_current_user
init
register_sidebar
wp_loaded
send_headers
parse_query
pre_get_posts
wp
template_redirect
get_header
wp_head

サンプルコード

サンプルコード1: 全ての投稿でnoindexを設定する

このサンプルは、全ての投稿に対してnoindexを設定するためにwp_robotsフィルタを利用します。

add_filter('wp_robots', function($robots) {
    $robots['noindex'] = true;
    return $robots;
});

引用元: https://developer.wordpress.org/reference/hooks/wp_robots/

サンプルコード2: 特定の投稿タイプにnoindexを設定する

このコードは、特定の投稿タイプ「portfolio」に対してnoindexを設定します。

add_filter('wp_robots', function($robots, $post) {
    if ($post->post_type === 'portfolio') {
        $robots['noindex'] = true;
    }
    return $robots;
}, 10, 2);

引用元: https://developer.wordpress.org/reference/hooks/wp_robots/

サンプルコード3: 特定の条件でnoarchiveを追加する

特定の条件が満たされた場合にnoarchiveを追加する例です。

add_filter('wp_robots', function($robots) {
    if (is_single() && get_post_meta(get_the_ID(), '_noarchive', true)) {
        $robots['noarchive'] = true;
    }
    return $robots;
});

引用元: https://developer.wordpress.org/reference/hooks/wp_robots/

サンプルコード4: 投稿のステータスに応じたrobots設定

投稿が「draft」の場合にnoindexを設定します。

add_filter('wp_robots', function($robots, $post) {
    if ($post->post_status === 'draft') {
        $robots['noindex'] = true;
    }
    return $robots;
}, 10, 2);

引用元: https://developer.wordpress.org/reference/hooks/wp_robots/

サンプルコード5: カスタム条件でrobots設定を変更

特定のページテンプレートを使用している場合に、noindexを設定します。

add_filter('wp_robots', function($robots) {
    if (is_page_template('page-custom.php')) {
        $robots['noindex'] = true;
    }
    return $robots;
});

引用元: https://developer.wordpress.org/reference/hooks/wp_robots/

この関数について質問する


上の計算式の答えを入力してください