John Davidson

php - How to add classes to wp custom nav <li> and <a> elements

0 comments
Message:


I have custom nav, i did put custom classes on nav ul element, but i cant put on li and a elements. There is my code


functions.php:


    function wpb_custom_new_menu() {
register_nav_menu('primary_navigation',__( 'Main Menu' ));
}
add_action( 'init', 'wpb_custom_new_menu' );

function add_menu_list_item_class($classes, $item, $args) {
if (property_exists($args, 'list_item_class')) {
$classes[] = $args->list_item_class;
}
return $classes;
}
add_filter('nav_menu_css_class', 'add_menu_list_item_class', 1, 3);

header.php:


                <?php
wp_nav_menu( array(
'theme_location' => 'primary_navigation',
'container' => 'ul',
'menu_class' => 'navbar-nav mr-auto py-4 py-md-0',
'list_item_class' => 'nav-item',
'link_class' => 'nav-link'
));
?>


My Answer:
To add custom classes to the
  • and elements in your custom nav menu, you can modify the add_menu_list_item_class function in your functions.php file as follows:

    php
    function add_menu_list_item_class($classes, $item, $args) {
    if (property_exists($args, 'list_item_class')) {
    $classes[] = $args->list_item_class;
    }

    if (property_exists($args, 'link_class')) {
    $classes[] = $args->link_class;
    }

    return $classes;
    }
    add_filter('nav_menu_css_class', 'add_menu_list_item_class', 10, 3);


    In your header.php file, you can then update the wp_nav_menu function to include the 'link_class' parameter for adding a custom class to the
    elements:

    php
    wp_nav_menu( array(
    'theme_location' => 'primary_navigation',
    'container' => 'ul',
    'menu_class' => 'navbar-nav mr-auto py-4 py-md-0',
    'list_item_class' => 'nav-item',
    'link_class' => 'nav-link'
    ));
    ?>


    With these changes, you should be able to add custom classes to both the
  • and elements in your custom nav menu.
  • Rate this post

    4 of 5 based on 7174 votes

    Comments




    © 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
    Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us