WordPress餐厅菜单跳转异常:直接访问正常,链接点击跳转异常
我有一个WordPress餐厅网站,设有/lunch-menu/(午餐菜单)和/dinner-menu/(晚餐菜单)页面,还有一个/menu/页面,用于根据时间和日期将用户重定向到对应菜单页面。
午餐菜单的可用时间为周一至周五11:00-15:00,我通过以下PHP函数实现判断:
function is_weekday() { $day_of_week = date('N'); // 1(周一)至7(周日) return ($day_of_week >= 1 && $day_of_week <= 5); }
判断时间的函数:
// 检查美国中部时区当前时间是否早于15:00 function is_before_3pm() { $timezone = 'America/Chicago'; // 美国中部时区 $current_time = new DateTime(null, new DateTimeZone($timezone)); $time_3pm = new DateTime('3:00 PM', new DateTimeZone($timezone)); return $current_time < $time_3pm; }
重定向非管理员用户的函数:
// 根据美国中部时区的日期和时间,重定向非管理员用户 add_action('template_redirect', 'menu_redirect'); function menu_redirect() { // 检查用户是否为非管理员 if (!current_user_can('activate_plugins')) { // 可根据需要修改管理员权限 // 检查当前URL是否包含'/menu/' if (strpos($_SERVER['REQUEST_URI'], '/menu/') !== false) { // 检查是否为工作日且美国中部时区当前时间早于15:00 if (is_weekday() && is_before_3pm()) { wp_redirect('/lunch-menu/'); exit; } else { wp_redirect('/dinner-menu/'); exit; } } } }
该功能正常运行,但出现一个问题:当通过Elementor设置的链接(无论是内部内容链接还是硬编码链接)直接指向/lunch-menu/或/dinner-menu/时,用户会被重定向;但直接在浏览器地址栏输入这两个URL时,却不会出现重定向。我尝试了两种链接设置方式,结果一致,请问这是什么原因?
1. 代码逻辑的固有限制
当前的menu_redirect函数仅在用户访问/menu/页面时才会触发重定向,代码里的strpos($_SERVER['REQUEST_URI'], '/menu/') !== false条件明确限定了触发场景。因此直接输入/lunch-menu/或/dinner-menu/的URL时,不会触发任何重定向——这完全符合代码的设计逻辑。
2. Elementor链接的实际指向误差
你看到的“Elementor链接指向菜单页面时被重定向”,大概率是以下情况:
- 你在Elementor中设置的链接实际URL是
/menu/,只是链接文本显示为“午餐菜单”或“晚餐菜单”,导致你误以为是直接指向对应菜单页面; - 或者在Elementor选择内部页面时误操作,把链接指向了
/menu/而非目标菜单页面。
3. 浏览器缓存的干扰
如果之前访问过/menu/页面并被重定向,部分浏览器会缓存这个重定向记录。当点击Elementor的链接时,浏览器直接调用缓存的跳转规则,表现为“被重定向”;而手动输入URL时,浏览器会发起全新请求,不会使用缓存的重定向,因此没有跳转。
如果你的需求是禁止用户在非允许时间直接访问/lunch-menu/或/dinner-menu/,需要修改menu_redirect函数,添加对这两个页面的判断逻辑:
add_action('template_redirect', 'menu_redirect'); function menu_redirect() { if (!current_user_can('activate_plugins')) { $current_uri = $_SERVER['REQUEST_URI']; $is_menu_page = strpos($current_uri, '/menu/') !== false; $is_lunch_page = strpos($current_uri, '/lunch-menu/') !== false; $is_dinner_page = strpos($current_uri, '/dinner-menu/') !== false; // 保留原/menu/页面的重定向逻辑 if ($is_menu_page) { if (is_weekday() && is_before_3pm()) { wp_redirect('/lunch-menu/'); exit; } else { wp_redirect('/dinner-menu/'); exit; } } // 非允许时间访问午餐菜单,重定向到晚餐菜单 if ($is_lunch_page) { if (!(is_weekday() && is_before_3pm())) { wp_redirect('/dinner-menu/'); exit; } } // 允许时间内访问晚餐菜单,重定向到午餐菜单 if ($is_dinner_page) { if (is_weekday() && is_before_3pm()) { wp_redirect('/lunch-menu/'); exit; } } } }
如果只是想解决Elementor链接的问题,直接检查Elementor中链接的实际URL,确保是指向/lunch-menu/或/dinner-menu/而非/menu/,同时可以清除浏览器缓存测试。
内容的提问来源于stack exchange,提问作者Dan

