我一直在尝试使用自定义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:
Here is the code that I am aiming for:
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;
}