Wordpress - 如何在 wp_nav_menu 中显示指向 'private' 页面的链接?

Wordpress - how to show links to 'private' pages in wp_nav_menu?

在我的 WordPress 站点中,我需要在主导航中显示 private links(通过 wp_nav_menu),即使用户没有登录(我只是需要显示 link,而不是改变谁可以查看实际内容)。

我可以在别处执行此操作,使用 wp_list_pages and 指定我想要显示的 post_status(es),但我看不到如何将其应用到 wp_nav_menu

这个有效:

wp_list_pages(array(
    'title_li'      => '',
    'child_of'      => $page->ID,    
    'post_status'   => 'published,private'
));

有没有办法做类似的事情?

wp_nav_menu(array(
    'menu'              => 'primary',
    'theme_location'    => 'primary',
    'container'         => FALSE,
    'walker'            => new MegaMenuWalker
    'depth'             => 2));

到目前为止,我的搜索显示了一系列 post 处理结果以使用 wp_get_nav_menu_items 挂钩过滤掉私人页面(或草稿)的方法,但我还没有找到一些东西做相反的事情。

我想我可以做一个自定义查询来以这种方式抓取物品,但这不允许我使用我的自定义助行器。

诱人的是 wp_get_nav_menu_items( $menu, $args ) 确实允许我指定 post_status 参数,但是我只能应用自己的渲染器而不是能够使用助行器...除非有一些在 wp_nav_menu?

上下文之外使用 walker 的方法

wp_nav_menu 函数 仅遍历 所需菜单中的链接,而不会获取它们。从源代码 (line 270) 中可以看出,获取链接的函数仅获得 name/id/etc。菜单而不是任何其他参数。

来自manual

Displays a navigation menu created in the Appearance → Menus panel.

Given a theme_location parameter, the function displays the menu assigned to that location. If no such location exists or no menu is assigned to it, the parameter fallback_cb will determine what is displayed.

If not given a theme_location parameter, the function displays

  • the menu matching the ID, slug, or name given by the menu parameter;
  • otherwise, the first non-empty menu; otherwise (or if the menu given by menu is empty), output of the function given by the fallback_cb parameter (wp_page_menu(), by default);
  • otherwise nothing.

因此,您需要使用 WP 管理面板将这些私人页面添加到菜单中,或者创建您自己的功能来获取页面并构建菜单(请注意:不是 nav_walker 因为它只使用数据而不获取它)。

根据已接受的答案,私人页面 默认情况下不会显示在菜单构建器中 Here's a way to get around that issue.

这是在菜单构建器中显示私人页面的简短片段:

add_filter( 'nav_menu_meta_box_object', 'show_private_pages_menu_selection' );
/**
* Add query argument for selecting pages to add to a menu
*/
function show_private_pages_menu_selection( $args ){
    if( $args->name == 'page' ) {
        $args->_default_query['post_status'] = array('publish','private');
    }
    return $args;
}

将此添加到自定义插件或您的主题中 functions.php,您将能够将私人页面添加到任何菜单中。