通过filter给wp_nav_menu的li还有a添加class


Updated on: July 30, 2020 in Wordpress by

将以下代码添加到functions.php, 将其中的class修改为你自己的class即可。

// add classes on li
function codedocs_add_classes_on_li($classes) { $classes[] = 'nav-item'; return $classes;
}add_filter( 'nav_menu_css_class', 'codedocs_add_classes_on_li' );

//add active to current item
function codedocs_add_active_to_nav_class($classes) {
 if (in_array('current-menu-item', $classes)) {  $classes[] = 'active'; }
 return $classes;}add_filter( 'nav_menu_css_class', 'codedocs_add_active_to_nav_class' );

//add classes on anchor of wp nav menu
function codedocs_add_classes_on_anchor($atts) { $class = 'nav-link'; $atts['class'] = $class; return $atts;}
add_filter('nav_menu_link_attributes','codedocs_add_classes_on_anchor');