【问题标题】:WordPress: only showing the current page’s top-level parent’s sub-menu items from a custom nav menuWordPress:仅显示来自自定义导航菜单的当前页面的顶级父级子菜单项
【发布时间】:2017-12-21 15:30:19
【问题描述】:

我需要帮助来组合这两个代码:

这个:

<?php wp_nav_menu(
                array(
                    'theme_location'  => 'primary',
                    'container_class' => 'collapse navbar-collapse',
                    'container_id'    => 'navbarNavDropdown',
                    'menu_class'      => 'navbar-nav',
                    'fallback_cb'     => '',
                    'menu_id'         => 'main-menu',
                    'walker'          => new rorentrep_WP_Bootstrap_Navwalker(),
                )
            );
?>

还有这个(来自https://www.minddevelopmentanddesign.com/blog/showing-current-pages-parents-sub-menu-items-custom-nav-menu-wordpress/):

<?php
         $section_id = empty( $post->ancestors ) ? $post->ID : end( $post->ancestors );
         $locations = get_nav_menu_locations();
         $menu = wp_get_nav_menu_object( $locations[ 'primary' ] ); // 'primary' is our nav menu's name
         $menu_items = wp_get_nav_menu_items( $menu->term_id, array( 'post_parent' => $section_id ) );

             if( !empty( $menu_items ) ) {
                 echo '<ul class="section-submenu">';
                 foreach( $menu_items as $menu_item ) {
                 echo '<li><a href="' . $menu_item->url . '">' . $menu_item->title . '</a></li>';
             }
             echo '</ul>';
             }
?>

更准确地说,我希望第二个代码回显的链接显示为第一个代码。

我的页面结构是这样的:

Business
 - Sub page a
 - Sub page b
 - Sub page c

Private
 - Sub page x
 - Sub page y
 - Sub page z

每当我访问一个子页面的 Business 时,我希望菜单仅列出子页面 a-c,而当我访问子页面的 Private 时,我希望菜单仅列出子页面 x-z。

由于可以添加多个页面,我不想针对特定的页面 id。

这样做的主要原因是输出代码像 wp_nav_menu 一样使用 walker bootstrap nav 进行包装和嵌套(将当前类添加到 nav-items)。

【问题讨论】:

    标签: php wordpress navigation parent-child wp-nav-walker


    【解决方案1】:

    在您的 walker 类中,您可以设置每个级别的行为。然后在element方法中查看深度:start_el

    class Footer extends \Walker_Nav_Menu
    {
        function start_el(&$output, $item, $depth = 0, $args = array(), $id = 0)
        {
          if ($depth == 0) {
            $output .= '
            <li class="list-inline-item">
              <a href="' . $item->url . '" title="' . $item->title . '">
                ' .  $item->title  . '
              </a>
            </li>';
          }
        }
        function start_lvl( &$output, $depth = 0, $args = array() ) {
          $output.= '';
        }
        function end_lvl( &$output, $depth = 0, $args = array() ) {
          $output.= '';
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-15
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多