Add classes to Wordpress Menu ul element

2019-08-18 05:47发布

问题:

My site uses the WordPress Appearance > Menus to create the <ul> and sub elements for my navigation links.

I am using a function in functions.php to add the class navbar-nav to the <ul> element like this:

function add_link_atts($atts) {
    $atts['class'] = "nav-link";
return $atts;
}
add_filter( 'nav_menu_link_attributes', 'add_link_atts');

But how can I add 2 extra classes? namely nav-fill and w-100

I tried this but don't think its working:

function add_link_atts($atts) {
    $atts['class'] = "nav-link nav-fill w-100";
return $atts;
}
add_filter( 'nav_menu_link_attributes', 'add_link_atts');

How can I add these two extra classes?

回答1:

To add CSS classes to a WordPress menu, first go to Appearance > Menus in your WordPress theme.

Next, find the Screen Options tab at the top right of the screen. Click to open the panel, and check the box labelled CSS Classes.

If you want to add Class to your Menu.

function main_menu()
{   
    wp_nav_menu( array( 'theme_location' => 'main-menu', 'container'=> false, 'menu_class'=>'nav-link nav-fill w-100'
    ) );

}

if you want to add class to your menu a tag element:

function add_class_to_all_menu_anchors( $atts ) {
    $atts['class'] = 'nav-link nav-fill w-100';

    return $atts;
}
add_filter( 'nav_menu_link_attributes', 'add_class_to_all_menu_anchors', 10 );