如何将类添加到具有子菜单的标记的父级

时间:2014-02-09 作者:Ashley Briscoe

我一直在尝试使用自定义walker将一个类添加到子菜单的父a标记中。我当前使用的walker将该类添加到父类<li>, 是否有人知道如何调整此项以将类添加到父类中<a> 改为标记。

Here is the existing walker I am using:

class My_Walker_Nav_Menu extends Walker_Nav_Menu{
  public function display_element($el, &$children, $max_depth, $depth = 0, $args, &$output){
    $id = $this->db_fields[\'id\'];    

    if(isset($children[$el->$id]))
      $el->classes[] = \'toggle-sub-nav closed\';    

    parent::display_element($el, $children, $max_depth, $depth, $args, $output);
  }
}

Here is the code that is output:

screen shot of current code output

Here is the code that I am aiming for:

Screen shot of desired code output with class applied to the a tag

1 个回复
SO网友:Dushan

You can simply add this code snippet in your theme\'s functions.php file.

/* Add classes and other attributes to the anchor tags if list item is a parent */

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\'] = \'your-custom-class\'; //This is the main concern according to the question
    $atts[\'id\'] = \'your-custom-id\'; //Optional
    $atts[\'data-toggle\'] = \'dropdown\'; //Optional
    $atts[\'data-target\'] = \'#\'; //Optional
  }
  return $atts;
}
结束

相关推荐

Add Protocol to Custom Menus

我一直在使用tel: 自定义菜单中的链接与响应性设计相结合,为我的智能手机主题添加了“立即呼叫”按钮。它一直运行良好。一位客户刚刚要求我也添加一个“发送文本”按钮。我想我会用sms: 它似乎有可接受的设备支持。然而,当我保存菜单时,WordPress将其从URL中删除。经过研究,我得出结论,这与esc_url() 和/或wp_kses() (参见Trac ticket #18268). 我编造了以下代码,试图自己添加SMS协议并将其放入函数中。php:<?php function add_n