【问题标题】:How to add class and element to <a>-tag in sub-menu of "wp_nav_menu" in WordPress?如何在 WordPress 的“wp_nav_menu”子菜单中的 <a>-tag 中添加类和元素?
【发布时间】:2012-10-21 02:28:53
【问题描述】:

我想在链接内的sub-menub 标记的a 标记中添加一个类。

WordPress 给了我这个代码:

<li id="menu-item-72" class="menu-item menu-item-type-post_type menu-item-object-page dropdown menu-item-72"><a
    href="#">Link</a>
  <ul class="dropdown-menu"></ul>

我想要这个:

<li id="menu-item-72" class="menu-item menu-item-type-post_type menu-item-object-page dropdown menu-item-72"> <a
    href="#" class="dropdown-toggle" data-toggle="dropdown">Link <b class="caret"></b></a>
  <ul class="dropdown-menu"></ul>

有人知道解决办法吗?

【问题讨论】:

    标签: wordpress wordpress-theming submenu menu-items wp-nav-menu-item


    【解决方案1】:

    看看这个答案,它解释了如何将自定义 HTML 添加到 wordpress 菜单:https://stackoverflow.com/a/12251157/1627227

    编辑:

    我已经整理了一个示例来满足您的问题。你可以把它放到functions.php中。请注意 cmets,它们解释了在何处添加您的自定义代码。

    class Custom_Walker_Nav_Menu extends Walker_Nav_Menu {
    
      function start_lvl(&$output, $depth) {
          $indent = str_repeat("\t", $depth);
          //$output .= "\n$indent<ul class=\"sub-menu\">\n";
    
          // Change sub-menu to dropdown menu
          $output .= "\n$indent<ul class=\"dropdown-menu\">\n";
      }
    
      function start_el ( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
        // Most of this code is copied from original Walker_Nav_Menu
        global $wp_query, $wpdb;
        $indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';
    
        $class_names = $value = '';
    
        $classes = empty( $item->classes ) ? array() : (array) $item->classes;
        $classes[] = 'menu-item-' . $item->ID;
    
        $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args ) );
        $class_names = ' class="' . esc_attr( $class_names ) . '"';
    
        $id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args );
        $id = strlen( $id ) ? ' id="' . esc_attr( $id ) . '"' : '';
    
        $has_children = $wpdb->get_var("SELECT COUNT(meta_id)
                                FROM wp_postmeta
                                WHERE meta_key='_menu_item_menu_item_parent'
                                AND meta_value='".$item->ID."'");
    
        $output .= $indent . '<li' . $id . $value . $class_names .'>';
    
        $attributes  = ! empty( $item->attr_title ) ? ' title="'  . esc_attr( $item->attr_title ) .'"' : '';
        $attributes .= ! empty( $item->target )     ? ' target="' . esc_attr( $item->target     ) .'"' : '';
        $attributes .= ! empty( $item->xfn )        ? ' rel="'    . esc_attr( $item->xfn        ) .'"' : '';
        $attributes .= ! empty( $item->url )        ? ' href="'   . esc_attr( $item->url        ) .'"' : '';
    
        // Check if menu item is in main menu
        if ( $depth == 0 && $has_children > 0  ) {
            // These lines adds your custom class and attribute
            $attributes .= ' class="dropdown-toggle"';
            $attributes .= ' data-toggle="dropdown"';
        }
    
        $item_output = $args->before;
        $item_output .= '<a'. $attributes .'>';
        $item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;
    
        // Add the caret if menu level is 0
        if ( $depth == 0 && $has_children > 0  ) {
            $item_output .= ' <b class="caret"></b>';
        }
    
        $item_output .= '</a>';
        $item_output .= $args->after;
    
        $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
      }
    
    }
    

    完成此操作后,您必须转到调用菜单 (wp_nav_menu()) 的位置。在我链接到的答案中,有对wp_nav_menu 的完整函数调用。但是,您必须将这一行:'walker' =&gt; new Custom_Walker_Nav_Menu 添加到参数数组中,才能在该特定菜单上使用您的自定义 walker 对象。

    希望你明白了;)

    【讨论】:

    • 对不起,我不明白。我应该在哪里插入父元素的“class="dropdown-toggle" data-toggle="dropdown""?以及链接内的 b-tag 在哪里?
    • 我添加了一个示例,它将您想要的更改应用于代码。如果还有什么不清楚的地方,请告诉我,是您手工编写了主题,还是使用了下载的主题。代码还需要,您正在使用WordPress Menuswp_nav_menu 来调用您的菜单。
    • 啊,非常感谢!但我只需要父菜单项中的“下拉菜单”类。属性“data-toggle="dropdown"”应该只出现在父菜单项的链接中。在此链接中,我需要此代码:&lt;b class="caret"&gt;&lt;/b&gt; 在子菜单的&lt;ul&gt; 中,我需要“下拉菜单”类问题是:我如何检查是否有子菜单或菜单项是父项吗?
    • 真的很抱歉,我错过了插入符号,并且 HTML 语法也有错误。我已经编辑了上面的代码。您可以通过$depth-Variable 确定您是否在主菜单中。 $depth为菜单层级,主菜单为0,层级越深,数字越大。
    • 谢谢,但现在我在每个深度=0 的项目中都有属性和类。只有当有子菜单时我才需要它们。有一个变量吗?
    【解决方案2】:

    从 Wordpress 3.6.0 开始,您可以使用 nav_menu_link_attributes 过滤器:

    add_filter( 'nav_menu_link_attributes', 'add_class_to_items_link', 10, 3 );
    
    function add_class_to_items_link( $atts, $item, $args ) {
      // check if the item has children
      $hasChildren = (in_array('menu-item-has-children', $item->classes));
      if ($hasChildren) {
        // add the desired attributes:
        $atts['class'] = 'dropdown-toggle';
        $atts['data-toggle'] = 'dropdown';
        $atts['data-target'] = '#';
      }
      return $atts;
    }
    

    不幸的是,这些标签没有我们可以使用的过滤器,所以我们需要一个 walker:

    class MY_Menu_Walker extends Walker_Nav_Menu {
    
      public function start_lvl( &$output, $depth = 0, $args = array() ) {
        $indent = str_repeat("\t", $depth);
        $output .= "\n$indent<ul class=\"sub-menu dropdown-menu\">\n";
      }   
    
    }
    

    然后在调用菜单时添加walker选项:

    wp_nav_menu( array('walker' => new MY_Menu_Walker)); 
    

    【讨论】:

    • 我只使用第一个代码 sn-p 就可以成功。谢谢@VictorBV
    【解决方案3】:

    在 Function.php 中使用此代码

    function add_menuclass($ulclass) {
       return preg_replace('/<a /', '<a class="list-group-item"', $ulclass);
    }
    add_filter('wp_nav_menu','add_menuclass');
    

    【讨论】:

      【解决方案4】:

      您可以使用它来检查是否有子菜单:

      $has_children = $wpdb->get_var("SELECT COUNT(meta_id)
                                      FROM wp_postmeta
                                      WHERE meta_key='_menu_item_menu_item_parent'
                                      AND meta_value='".$item->ID."'");
      

      然后做简单的检查

      if ( $has_children > 0 ) {
        // These lines adds your custom class and attribute
        $attributes .= ' class="dropdown-toggle"';
        $attributes .= ' data-toggle="dropdown"';
      }
      

      记得将 $wpdb 设置为全局:

      global $wp_query, $wpdb;
      

      多田~

      【讨论】:

        【解决方案5】:

        你可以把它放到functions.php中。

        class My_Walker_Nav_Menu extends Walker_Nav_Menu {
            function display_element( $element, &$children_elements, $max_depth, $depth=0, $args, &$output ){
              $GLOBALS['dd_children'] = ( isset($children_elements[$element->ID]) )? 1:0;
              $GLOBALS['dd_depth'] = (int) $depth;
              parent::display_element( $element, $children_elements, $max_depth, $depth, $args, $output );
            }
           function start_lvl(&$output, $depth) {
             $indent = str_repeat("\t", $depth);
             $output .= "\n$indent<ul class=\"dropdown-menu\">\n";
           }
          function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) 
          {
            global $wp_query, $wpdb;
            $indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';
            $li_attributes = '';
            $class_names = $value = '';
            $classes = empty( $item->classes ) ? array() : (array) $item->classes;
        
            //Add class and attribute to LI element that contains a submenu UL.
            if ($args->has_children){
              $classes[]    = 'dropdown';
              $li_attributes .= 'data-dropdown="dropdown"';
            }
            $classes[] = 'menu-item-' . $item->ID;
            //If we are on the current page, add the active class to that menu item.
            $classes[] = ($item->current) ? 'active' : '';
            //Make sure you still add all of the WordPress classes.
            $class_names = join( ' ', apply_filters( 'nav_menu_css_class',     array_filter( $classes ), $item, $args ) );
            $class_names = ' class="' . esc_attr( $class_names ) . '"';
            $id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args );
            $id = strlen( $id ) ? ' id="' . esc_attr( $id ) . '"' : '';
            $has_children = $wpdb->get_var(
            $wpdb->prepare("
               SELECT COUNT(*) FROM $wpdb->postmeta
               WHERE meta_key = %s
               AND meta_value = %d
               ", '_menu_item_menu_item_parent', $item->ID)
             );
           $output .= $indent . '<li' . $id . $value . $class_names .'>';
           $output .= $indent . '<li' . $id . $value . $class_names . $li_attributes . '>';
           //Add attributes to link element.
           $attributes  = ! empty( $item->attr_title ) ? ' title="'  . esc_attr( $item->attr_title ) .'"' : '';
           $attributes .= ! empty( $item->target ) ? ' target="' . esc_attr( $item->target     ) .'"' : '';
           $attributes .= ! empty( $item->xfn ) ? ' rel="'    . esc_attr( $item->xfn        ) .'"' : '';
           $attributes .= ! empty( $item->url ) ? ' href="'   . esc_attr( $item->url        ) .'"' : '';
           // Check if menu item is in main menu
        
        if ( $depth == 0 && $has_children > 0  ) {
            // These lines adds your custom class and attribute
            $attributes .= ' class="dropdown-toggle"';
            $attributes .= ' data-toggle="dropdown"';
        }
           $item_output = $args->before;
           $item_output .= '<a'. $attributes .'>';
           $item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;
           // Add the caret if menu level is 0
           if ( $depth == 0 && $has_children > 0  ) {
              $item_output .= ' <b class="caret"></b>';
           }
           $item_output .= '</a>';
           $item_output .= $args->after;
           $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
          }
        }
        

        然后在您要显示此菜单的模板中放置此代码。

           <?php
        
                        if ( has_nav_menu( 'primary' ) ) {
        
                             $defaults = array(
                                'theme_location'  => 'primary',
                                //'menu'            => '',
                                 'container'       => 'ul',
                                 'container_class' => '',
                                 'container_id'    => '',
                                 'menu_class'      => '',
                                 'menu_id'         => '',
                                 'walker'          =>  new My_Walker_Nav_Menu()
                            );
        
                            wp_nav_menu( $defaults );
        
                        }
                    ?> 
        

        使用这个我解决了我的问题。

        【讨论】:

          猜你喜欢
          • 2012-09-03
          • 2016-10-15
          • 2018-08-18
          • 1970-01-01
          • 2018-03-20
          • 2012-07-06
          • 2021-10-30
          • 2013-01-06
          • 1970-01-01
          相关资源
          最近更新 更多