WooCommerce未登录用户访问商品页跳转登录后回跳原页实现问题
解决方案
第一步:修改未登录访问商品的跳转逻辑,携带目标回跳地址
替换你当前使用的跳转代码为以下内容,跳转登录页时将当前商品页URL作为参数传递:
add_action('template_redirect', 'ethis_redirect_for_loggedin_users'); function ethis_redirect_for_loggedin_users() { if ( !is_user_logged_in() && is_product() ) { // 编码当前商品页URL作为回跳目标 $redirect_target = urlencode( get_permalink() ); wp_redirect( site_url( '/default-login?redirect_to=' . $redirect_target ) ); exit; } }
第二步:新增登录后重定向规则,读取参数完成回跳
添加以下过滤器,登录成功后自动识别携带的目标地址跳转:
add_filter('login_redirect', 'custom_product_login_redirect', 10, 3); function custom_product_login_redirect($default_redirect, $request, $user) { // 校验redirect_to参数合法性后跳转 if (isset($_GET['redirect_to'])) { $target_url = urldecode($_GET['redirect_to']); if (wp_http_validate_url($target_url)) { return $target_url; } } // 无有效参数时返回默认跳转地址 return $default_redirect; }
注意事项
- 如果你使用的自定义登录页表单没有自动读取URL参数的逻辑,需要在登录表单内添加隐藏域,保证参数在登录提交时正常传递:
<input type="hidden" name="redirect_to" value="<?php echo isset($_GET['redirect_to']) ? esc_attr($_GET['redirect_to']) : ''; ?>"> - 原有方案失效的核心原因是
HTTP_REFERER可靠性极低,跳转至登录页后该值会被覆盖为登录页地址,因此不能用该字段作为回跳依据。
内容的提问来源于stack exchange,提问作者Akramul Hasan
相关产品推荐
相关产品推荐

