Woocommerce如何在template_redirect钩子中排除myaccount的子端点页面
问题根因
你的代码失效核心是is_page()函数的特性限制:
WordPress的is_page()仅支持传入单页的ID、别名、标题进行判断,所有/my-account/下的子端点本质都归属于「我的账户」这一个父页面,所以is_page('my-account/lost-password/')永远返回false,你加的排除条件根本不会生效,导致未登录用户访问所有myaccount下的页面都会触发重定向。
正确实现方案
方案1:WooCommerce场景专用(推荐)
直接用WooCommerce内置的is_wc_endpoint_url()函数判断端点,性能和兼容性最好:
add_action( 'template_redirect', 'wish_custom_redirect' ); function wish_custom_redirect() { // 未登录 + 访问我的账户页面 + 不在排除的端点列表内 才触发重定向 if ( !is_user_logged_in() && is_page('my-account') && !is_wc_endpoint_url( 'lost-password' ) && !is_wc_endpoint_url( 'reset-password' ) // 有其他要排除的端点可以按上面格式新增 ) { wp_redirect( home_url('/') ); exit; } }
你之前写的登出重定向代码可以保留,和上面的逻辑不冲突,两者配合即可覆盖所有场景。
方案2:通用场景(非WooCommerce自定义端点适用)
如果你没有用WooCommerce,是自行配置的自定义端点,可以通过匹配当前请求路径实现排除:
add_action( 'template_redirect', 'wish_custom_redirect' ); function wish_custom_redirect() { global $wp; $current_request = $wp->request; // 定义不需要重定向的myaccount子路径 $exclude_paths = [ 'my-account/lost-password', 'my-account/reset-password' ]; $is_exclude = false; foreach ($exclude_paths as $path) { if (strpos($current_request, $path) !== false) { $is_exclude = true; break; } } if ( !is_user_logged_in() && is_page('my-account') && !$is_exclude ) { wp_redirect( home_url('/') ); exit; } }
内容的提问来源于stack exchange,提问作者libertarian
相关产品推荐
相关产品推荐

