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

概要

wp_safe_redirect関数は、指定されたURLが有効か調べ、リダイレクトするための関数です。この関数は、特にセキュリティを考慮したリダイレクトを実装する際に利用されます。具体的には、以下のような状況で使用されることが一般的です。

  1. ユーザーがログイン後のリダイレクト
  2. サイトの別のページへのナビゲーション
  3. セキュリティ制限されたアクセスの制御
  4. 不正なリクエストからの保護
  5. URLの正当性を確認することでのエラー防止
  6. プラグイン設定の変更後のリダイレクト
  7. サイトメンテナンス中のユーザーガイダンス
  8. 特定の条件下でのユーザーエクスペリエンスの向上

構文

wp_safe_redirect( string $location, int $status = 302 );

パラメータ

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

戻り値

この関数はリダイレクトを実行し、何も返さない(null)です。

関連する関数

使用可能なワードプレスのバージョン

この関数はWordPress 2.8以降で使用可能です。

コアファイルのパス

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. 基本的なリダイレクトの例

    if ( ! is_user_logged_in() ) {
       wp_safe_redirect( home_url() );
       exit;
    }
    

    説明: ユーザーがログインしていない場合、ホームページにリダイレクトします。

  2. 特定のページにリダイレクトする例

    function redirect_to_dashboard() {
       wp_safe_redirect( admin_url() );
       exit;
    }
    add_action( 'admin_init', 'redirect_to_dashboard' );
    

    説明: 管理画面の初期化時にダッシュボードにリダイレクトします。

  3. エラーメッセージ付きのリダイレクト

    function redirect_with_message() {
       if ( isset( $_GET['error'] ) ) {
           wp_safe_redirect( add_query_arg( 'message', 'error_message', home_url() ) );
           exit;
       }
    }
    add_action( 'init', 'redirect_with_message' );
    

    説明: エラーが発生した場合、メッセージ付きでホームページにリダイレクトします。

  4. 条件に基づくリダイレクト

    function condition_based_redirect() {
       if ( current_user_can( 'administrator' ) ) {
           wp_safe_redirect( admin_url() );
           exit;
       }
    }
    add_action( 'init', 'condition_based_redirect' );
    

    説明: 管理者であれば管理画面にリダイレクトします。

  5. 外部サイトへのリダイレクトの例

    function external_redirect() {
       wp_safe_redirect( 'https://www.example.com' );
       exit;
    }
    add_action( 'template_redirect', 'external_redirect' );
    

    説明: テンプレートのリダイレクト時に外部サイトへ移動します。

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


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