ワードプレスのwp_redirect関数の使用方法・解説

概要

wp_redirect関数は、WordPressにおいて指定されたURLへリダイレクトする際に使用される関数です。一般的に以下のような機能を実装する際に利用されます。

  1. ユーザーが特定のページにアクセスした際に別のページへ転送する
  2. パスワード保護されたコンテンツへのアクセスを制御する
  3. 古いURLから新しいURLへの301リダイレクトを行う
  4. ユーザーの権限に基づくページのリダイレクト
  5. フィルタリングされた検索結果ページへのリダイレクト
  6. 特定のクッキーが存在しない場合のリダイレクト
  7. 投稿のステータス変更時のリダイレクト
  8. ショートコードやウィジェットからのリンク先の変更時のリダイレクト

構文

wp_redirect( string $location, int $status = 302 )

パラメータ

  • $location (string): リダイレクト先のURL。
  • $status (int): HTTPステータスコード。デフォルトは302(Found)。

戻り値

この関数は、成功時に何も返しません。ただし、HTTPヘッダーを送信します。

関連する関数

使用可能なバージョン

wp_redirect関数はバージョン1.2以降で利用可能です。

コアファイルのパス

この関数はwp-includes/pluggable.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: 基本的なリダイレクト

function my_custom_redirect() {
    wp_redirect('https://example.com/new-url');
    exit;
}
add_action('template_redirect', 'my_custom_redirect');

このコードは、現在のページが読み込まれた後に指定したURLにリダイレクトします。template_redirectアクションを使用しています。

サンプルコード2: 301リダイレクト

function my_permanent_redirect() {
    wp_redirect('https://example.com/permanent-url', 301);
    exit;
}
add_action('init', 'my_permanent_redirect');

このコードは、リダイレクトタイプを301に設定して、指定されたURLに恒久的にリダイレクトします。

サンプルコード3: ログイン後のリダイレクト

function my_login_redirect($redirect_to, $request, $user) {
    return 'https://example.com/dashboard';
}
add_filter('login_redirect', 'my_login_redirect', 10, 3);

このコードは、ユーザーがログインした後、ダッシュボードページにリダイレクトします。

サンプルコード4: 不正アクセス時のリダイレクト

function my_restrict_access() {
    if (!is_user_logged_in()) {
        wp_redirect('https://example.com/login');
        exit;
    }
}
add_action('template_redirect', 'my_restrict_access');

このコードは、ログインしていないユーザーがアクセスした場合に、ログインページへリダイレクトします。

サンプルコード5: 特定の条件でのリダイレクト

function my_conditional_redirect() {
    if (is_page('old-page')) {
        wp_redirect('https://example.com/new-page');
        exit;
    }
}
add_action('template_redirect', 'my_conditional_redirect');

このコードは、特定のページ(old-page)にアクセスした際に、新しいページ(new-page)へリダイレクトします。

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


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