WordPress.org

Ready to get started?Download WordPress

Codex

Attention Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Plugin API/Filter Reference/nav menu link attributes

Description

The nav menu link attributes filter allows themers and developers full control over what HTML attributes are added to menus generated with the WP Menu API.

This filter runs per nav item, vs providing a list of all nav elements at once.

Usage

When the 'nav menu link attributes' filter is called, it is passed three parameters:

  • $atts - HTML attributes in an associative array
  • $item - Object containing item details. E.G: If the link is to a page $item will be a WP_Post object
  • $args - Array containing config with desired markup of nav item
add_filter( 'nav_menu_link_attributes', 'filter_function_name', 10, 3 );

function filter_function_name( $atts, $item, $args ) {
    // Manipulate attributes
    return $atts;
}

Where 'filter_function_name' is the function WordPress should call when filter is run. Note that the filter function must return a value after it is finished processing or the result will be empty.

filter_function_name should be unique function name. It cannot match any other function name already declared.

Examples

The following example adds an attribute to all <a> tags in the wp_nav_menu

function add_menu_atts( $atts, $item, $args ) {
	$atts['onClick'] = 'return true';
    return $atts;
}
add_filter( 'nav_menu_link_attributes', 'add_menu_atts', 10, 3 );

The following example adds an attribute to specific menu items (34 and 39). Specify the ID of each menu item as an array.

function add_specific_menu_atts( $atts, $item, $args ) {
	$menu_items = array(34,39);
	if (in_array($item->ID, $menu_items)) {
	  $atts['onClick'] = 'return false';
	}
	
    return $atts;
}
add_filter( 'nav_menu_link_attributes', 'add_specific_menu_atts', 10, 3 );

Change Log

See Also