How to add link_class to wp_nav_menu

Posted on: April 24th, 2023
By: Tadeo Martinez

Add the following code in your functions.php

function add_menu_link_class( $atts, $item, $args ) {
    if( isset($args->link_class) ) {
        $atts['class'] = $args->link_class;
    }
    return $atts;
}
add_filter( 'nav_menu_link_attributes', 'add_menu_link_class', 10, 3 );

When adding the wp_nav_menu, now you can use the ‘link_class’ parameter.

<?php
wp_nav_menu( array(
  'menu' => 'Your Menu Name',
  'menu_class' => 'your-menu-class',
  'container' => 'nav',
  'container_class' => 'your-container-class',
  'link_class' => 'your-link-class',
) );
?>

These are the native parameters:

wp_nav_menu(
array(
    'theme_location'  => 'header-menu',
    'menu'            => '',
    'container'       => 'div',
    'container_class' => 'menu-{menu slug}-container',
    'container_id'    => '',
    'menu_class'      => 'menu',
    'menu_id'         => '',
    'echo'            => true,
    'fallback_cb'     => 'wp_page_menu',
    'before'          => '',
    'after'           => '',
    'link_before'     => '',
    'link_after'      => '',
    'items_wrap'      => '<ul>%3$s</ul>',
    'depth'           => 0,
    'walker'          => ''
    )
);

Have any questions or comments? Write them below!


Leave a Reply

Your email address will not be published. Required fields are marked *