概要
woocommerce_login_redirect
フィルタは、WooCommerce のユーザーログイン後にリダイレクトされるURLをカスタマイズするために使用されます。ログインプロセスの後、ユーザーが特定のページにリダイレクトされるよう調整する際によく使われます。
このフィルタは、以下のような機能を実装する際に役立ちます。
- ログイン後のリダイレクト先URLを変更する
- ユーザーの役割に応じたリダイレクトを設定する
- 特定の条件(例えばメールアドレスのドメインなど)に基づいてリダイレクト先を変える
- デフォルトのリダイレクト先とは異なるURLにユーザーを誘導する
- ショッピングカートが存在する場合に特定のページにリダイレクトする
- カスタムページに移動する特定のユーザーグループを作成する
構文
add_filter('woocommerce_login_redirect', 'your_function', 10, 2);
パラメータ
- $redirect (string): デフォルトのリダイレクトURL。
- $user (WP_User): ログイン中のユーザーオブジェクト。
戻り値
このフィルタは、ログイン後のリダイレクト先URLを返します。
使用可能なバージョン
- WooCommerce: 3.0以上
- WordPress: 4.0以上
この関数のアクションでの使用可能性
アクション | 使用例 |
---|---|
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
add_filter('woocommerce_login_redirect', 'custom_login_redirect', 10, 2);
function custom_login_redirect($redirect, $user) {
// ユーザーの役割が 'customer' の場合、特定のページにリダイレクト
if (in_array('customer', (array) $user->roles)) {
return home_url('/customer-dashboard/');
}
return $redirect;
}
このコードは、顧客ユーザーがログインした際に「/customer-dashboard/」にリダイレクトします。
サンプルコード 2
add_filter('woocommerce_login_redirect', 'redirect_after_login', 10, 2);
function redirect_after_login($redirect, $user) {
// 'editor' の役割を持つユーザーを管理画面にリダイレクト
if (in_array('editor', (array) $user->roles)) {
return admin_url();
}
return $redirect;
}
このコードは、エディターロールを持つユーザーを管理画面にリダイレクトします。
サンプルコード 3
add_filter('woocommerce_login_redirect', 'conditional_redirect', 10, 2);
function conditional_redirect($redirect, $user) {
// 特定のメールドメインを持つユーザーを特定のページにリダイレクト
$allowed_email = '@example.com';
if (strpos($user->user_email, $allowed_email) !== false) {
return home_url('/welcome-page/');
}
return $redirect;
}
このコードは、特定のメールドメインのユーザーを「/welcome-page/」にリダイレクトします。
サンプルコード 4
add_filter('woocommerce_login_redirect', 'cart_based_redirect', 10, 2);
function cart_based_redirect($redirect, $user) {
// カートにアイテムがある場合、カートページにリダイレクト
if (WC()->cart->get_cart_contents_count() > 0) {
return wc_get_cart_url();
}
return $redirect;
}
このコードは、カートにアイテムがある場合にカートページにリダイレクトします。
サンプルコード 5
add_filter('woocommerce_login_redirect', 'special_user_redirect', 10, 2);
function special_user_redirect($redirect, $user) {
// ロールが 'subscriber' の場合、プロフィールページにリダイレクト
if (in_array('subscriber', (array) $user->roles)) {
return home_url('/my-profile/');
}
return $redirect;
}
このコードは、サブスクリバーロールを持つユーザーを「/my-profile/」にリダイレクトします。