如何基于特定用户元字段限制WordPress菜单仅对研究者可见?
问题:仅对特定用户显示WordPress主导航中的「Research」菜单项
需求说明:
- WordPress主导航(primary位置)中有一个「Research」菜单项,仅对选中了用户元字段
wpum_relationship_to_lib中researcher选项的用户显示 wpum_relationship_to_lib是多选字段,可选值包括researcher、student、employee等,且不属于WordPress角色- 未登录用户需隐藏该菜单项
以下是我编写的无法正常生效的代码:
function restrict_menu_to_researchers($items, $args) { // Check if the menu is assigned to the desired location if ($args->theme_location === 'primary') { // Check if the user is logged in if (is_user_logged_in()) { $user_id = get_current_user_id(); $relationship_values = get_user_meta($user_id, 'wpum_relationship_to_lib', true); // Check if the user is the "researcher" if (is_array($relationship_values) && in_array('researcher', $relationship_values)) { // Allow the menu for researchers return $items; } else { foreach ($items as $key => $item) { if ($item->title == 'Research') { // Hide the "Research" menu for non-researchers unset($items[$key]); } } } } else { foreach ($items as $key => $item) { if ($item->title == 'Research') { // Hide the "Research" menu for non-logged-in users unset($items[$key]); } } } } return $items; } add_filter('wp_nav_menu_objects', 'restrict_menu_to_researchers', 10, 2);
修正后的代码
function restrict_menu_to_researchers($items, $args) { // 验证是否为目标主导航位置 if ($args->theme_location === 'primary') { $show_research_menu = false; // 检查用户登录状态 if (is_user_logged_in()) { $user_id = get_current_user_id(); // 多选字段需传false获取完整值数组 $relationship_values = get_user_meta($user_id, 'wpum_relationship_to_lib', false); // 判断用户是否选中researcher选项 if (is_array($relationship_values) && in_array('researcher', $relationship_values)) { $show_research_menu = true; } } // 不符合条件则移除Research菜单项 if (!$show_research_menu) { foreach ($items as $key => $item) { // 同时匹配标题和slug,避免标题修改后失效 if ($item->title === 'Research' || $item->slug === 'research') { unset($items[$key]); } } } } return $items; } add_filter('wp_nav_menu_objects', 'restrict_menu_to_researchers', 10, 2);
关键修正点
- 修正用户元字段获取方式:将
get_user_meta的第三个参数从true改为false。因为wpum_relationship_to_lib是多选字段,WordPress会以数组形式存储选中值,传true仅会返回第一个选中值,导致无法正确判断用户是否选中了researcher。 - 优化逻辑结构:用
$show_research_menu变量统一控制显示状态,避免重复的循环移除代码,提升可读性和可维护性。 - 增加slug判断:除了匹配菜单标题,同时匹配菜单项的
slug——如果后续菜单标题被修改(如翻译),slug通常保持稳定,能确保判断逻辑持续有效。
内容的提问来源于stack exchange,提问作者Mary.fa
相关产品推荐
相关产品推荐

