【问题标题】:"current" class on top level menu item with wp_nav_menu带有 wp_nav_menu 的顶级菜单项上的“当前”类
【发布时间】:2013-08-10 06:31:55
【问题描述】:

我用 wp_nav_menu 创建了一个 wordpress 菜单。

我的结构如下:

  • 页面
    • 类别
  • 页面
  • 页面
  • 页面

如果我在“类别”中打开帖子,菜单的顶层没有“当前”类别——只有“类别”。仅在页面中嵌套在多级菜单上效果很好。

有没有办法解决这个问题?

【问题讨论】:

    标签: php wordpress


    【解决方案1】:

    1) 编写自定义 walker http://codex.wordpress.org/Function_Reference/wp_nav_menu#Using_a_Custom_Walker_Function 以在调用该类别时添加当前类;

    2) 或者,(不是最优雅的):找到您想要的菜单项的页面 ID - 在下面的示例中为 1000 - 突出显示为当前,选择该类别 - is_category - 然后添加当前类 - addClass - 使用 jQuery:

    <?php if (is_category('my-category')) { ?>
    
        <script type="text/javascript">
    
            jQuery(function($) {
            $(document).ready(function() {
            $('#menu-main-menu li.menu-item-1000').addClass('current-menu-item');
            }); });
    
            </script>
    
        <?php } ?>
    

    【讨论】:

      【解决方案2】:

      啊...在wordpress codex中找到了解决方案。这对我来说很好:

      add_filter( 'wp_nav_menu_objects', 'add_menu_parent_class' );
      function add_menu_parent_class( $items ) {
      
          $parents = array();
          foreach ( $items as $item ) {
              if ( $item->menu_item_parent && $item->menu_item_parent > 0 ) {
                  $parents[] = $item->menu_item_parent;
              }
          }
      
          foreach ( $items as $item ) {
              if ( in_array( $item->ID, $parents ) ) {
                  $item->classes[] = 'menu-parent-item'; 
              }
          }
      
          return $items;    
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-16
        • 1970-01-01
        • 2011-06-29
        相关资源
        最近更新 更多