钩子文档

nav_menu_link_attributes

💡 云策文档标注

概述

nav_menu_link_attributes 是一个 WordPress 过滤器,用于修改菜单项锚点元素的 HTML 属性。它允许开发者对通过 WP Menu API 生成的菜单链接属性进行精细控制,例如添加类、目标属性或自定义事件。

关键要点

  • 过滤器作用于每个菜单项,而非整个菜单列表,提供逐个处理的能力。
  • 参数包括 $atts(属性数组)、$menu_item(菜单项对象)、$args(wp_nav_menu 参数)和 $depth(深度),回调函数必须返回处理后的 $atts。
  • 可用于添加类、目标属性、ARIA 角色等,支持基于菜单项 ID、主题位置或深度等条件进行动态修改。
  • 从 WordPress 3.6.0 引入,4.1.0 版本增加了 $depth 参数。

代码示例

// 示例:为特定菜单项添加 onClick 属性
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 );

注意事项

  • 回调函数必须返回 $atts 数组,否则菜单链接属性可能为空。
  • 默认 Walker 菜单不会在锚点元素上添加 class 属性,需通过此过滤器手动添加。
  • 参数数量需根据使用情况调整,例如仅使用 $atts 时可只传递一个参数,但使用 $depth 时需传递所有四个参数。

📄 原文内容

Filters the HTML attributes applied to a menu item’s anchor element.

Parameters

$attsarray
The HTML attributes applied to the menu item’s <a> element, empty strings are ignored.

  • title string
    Title attribute.
  • target string
    Target attribute.
  • rel string
    The rel attribute.
  • href string
    The href attribute.
  • aria-current string
    The aria-current attribute.

$menu_itemWP_Post
The current menu item object.
$argsstdClass
An object of wp_nav_menu() arguments.

More Arguments from wp_nav_menu( … $args )

Array of nav menu arguments.

  • menu int|string|WP_Term
    Desired menu. Accepts a menu ID, slug, name, or object.
  • menu_class string
    CSS class to use for the ul element which forms the menu.
    Default 'menu'.
  • menu_id string
    The ID that is applied to the ul element which forms the menu.
    Default is the menu slug, incremented.
  • container string
    Whether to wrap the ul, and what to wrap it with.
    Default 'div'.
  • container_class string
    Class that is applied to the container.
    Default ‘menu-{menu slug}-container’.
  • container_id string
    The ID that is applied to the container.
  • container_aria_label string
    The aria-label attribute that is applied to the container when it’s a nav element.
  • fallback_cb callable|false
    If the menu doesn’t exist, a callback function will fire.
    Default is 'wp_page_menu'. Set to false for no fallback.
  • before string
    Text before the link markup.
  • after string
    Text after the link markup.
  • link_before string
    Text before the link text.
  • link_after string
    Text after the link text.
  • echo bool
    Whether to echo the menu or return it. Default true.
  • depth int
    How many levels of the hierarchy are to be included.
    0 means all. Default 0.
    Default 0.
  • walker object
    Instance of a custom walker class.
  • theme_location string
    Theme location to be used. Must be registered with register_nav_menu() in order to be selectable by the user.
  • items_wrap string
    How the list items should be wrapped. Uses printf() format with numbered placeholders. Default is a ul with an id and class.
  • item_spacing string
    Whether to preserve whitespace within the menu’s HTML.
    Accepts 'preserve' or 'discard'. Default 'preserve'.

$depthint
Depth of menu item. Used for padding.

More Information

  • The filter permits 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.
  • Note that the callback function must return a value after it is finished processing or the result will be empty.

Source

$atts       = apply_filters( 'nav_menu_link_attributes', $atts, $menu_item, $args, $depth );

Changelog

Version Description
4.1.0 The $depth parameter was added.
3.6.0 Introduced.

User Contributed Notes

  1. Skip to note 8 content

    Example migrated from Codex:

    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 );

    In the simplest instance above, the filter adds the attribute to all menu items of all menus. In case you only want to add the attributes to a certain menu location, you can check for menu location in a conditional.

  2. Skip to note 9 content

    Example migrated from Codex:

    The following function adds a class attribute to all <a> tags in a particular menu location (‘primary’).

    function add_specific_menu_location_atts( $atts, $item, $args ) {
        // check if the item is in the primary menu
        if( $args->theme_location == 'primary' ) {
          // add the desired attributes:
          $atts['class'] = 'menu-link-class';
        }
        return $atts;
    }
    add_filter( 'nav_menu_link_attributes', 'add_specific_menu_location_atts', 10, 3 );

  3. Skip to note 10 content

    The default Walker menu does not include a class attribute on the anchor (<a>) element, but one can easily be added using this filter.

    function add_class_to_all_menu_anchors( $atts ) {
    	$atts['class'] = 'menu-item-anchor';
    
        return $atts;
    }
    add_filter( 'nav_menu_link_attributes', 'add_class_to_all_menu_anchors', 10 );

    You might notice there that I am only passing one parameter ($atts) to the function. This is because we only need the $atts in this case and there is no need to pass other parameters. Alternatively, let’s say we wanted to add a class to all anchors which are not top level:

    function add_class_to_non_top_level_menu_anchors( $atts, $item, $args, $depth ) {
    	if ( 0 !== $depth ) {
    		$atts['class'] = 'menu-item-anchor-non-top';
    	}
    
    	return $atts;
    }
    add_filter( 'nav_menu_link_attributes', 'add_class_to_non_top_level_menu_anchors', 10, 4 );

    In this case, we need to pass all four parameters because we are using the $depth parameter.

  4. Skip to note 12 content

    Example migrated from Codex:

    The following function adds a class to all menu items that have “Open link in a new window/tab” checked in the menu options.

    function add_class_to_target_blank_menu_items( $atts, $item, $args ) {
        // check if the item is set to target="_blank"
        if ( $item->target == '_blank' ) {
          // add the desired attributes:
          $atts['class'] = 'target-blank';
        }
        return $atts;
    }
    add_filter( 'nav_menu_link_attributes', 'add_class_to_target_blank_menu_items', 10, 3 );

  5. Skip to note 13 content

    I have solution to add class to anchor tag.

    1: Step: add this in functions.php

    function add_additional_class_on_a($classes, $item, $args)
    {
    	if (isset($args->add_a_class)) {
    		$classes['class'] = $args->add_a_class;
    	}
    	return $classes;
    }
    
    add_filter('nav_menu_link_attributes', 'add_additional_class_on_a', 1, 3);

    2: Then use it like this

     'my-footer-menu',
    			'container_id'    => '',
    			'menu_class'      => 'footer-top list-unstyled',
    			'menu_id'         => '',
    			'add_a_class'     => 'box-link text-dark',
    		));
    ?>