概要
wp_redirect
関数は、WordPressにおいて指定されたURLへリダイレクトする際に使用される関数です。一般的に以下のような機能を実装する際に利用されます。
- ユーザーが特定のページにアクセスした際に別のページへ転送する
- パスワード保護されたコンテンツへのアクセスを制御する
- 古いURLから新しいURLへの301リダイレクトを行う
- ユーザーの権限に基づくページのリダイレクト
- フィルタリングされた検索結果ページへのリダイレクト
- 特定のクッキーが存在しない場合のリダイレクト
- 投稿のステータス変更時のリダイレクト
- ショートコードやウィジェットからのリンク先の変更時のリダイレクト
構文
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)へリダイレクトします。