nav_menu_item_args
Allows you to change the arguments of an individual navigation menu item in wp_nav_menu().
Usage
add_filter( 'nav_menu_item_args', 'wp_kama_nav_menu_item_args_filter', 10, 3 );
/**
* Function for `nav_menu_item_args` filter-hook.
*
* @param stdClass $args An object of wp_nav_menu() arguments.
* @param WP_Post $menu_item Menu item data object.
* @param int $depth Depth of menu item. Used for padding.
*
* @return stdClass
*/
function wp_kama_nav_menu_item_args_filter( $args, $menu_item, $depth ){
// filter...
return $args;
}
- $args(stdClass)
Object containing arguments passed to wp_nav_menu().
For example:
- $item(WP_Post)
Object containing menu item data. For example:
- $depth(int)
- Menu item level. Added in version 4.1.0 and used for indentation. Top-level items have
$depth = 0, their children have$depth = 1, and so on.
Examples
#1 Add icons to menu items
Add an icon to links in the menu assigned to the primary location:
function change_menu_item_args( $args ) {
if ( $args->theme_location == 'primary' ) {
$args->link_before = '<span class="dashicons dashicons-admin-links"></span>';
}
return $args;
}
add_filter( 'nav_menu_item_args', 'change_menu_item_args' );
Add an icon to links in every menu when the menu item is a page; other items are output normally:
function change_menu_item_args( $args, $item ) {
if ( $item->object == 'page' ) {
$args->link_before = '<span class="dashicons dashicons-admin-links"></span>';
}
return $args;
}
add_filter( 'nav_menu_item_args', 'change_menu_item_args', 10, 2 );
Add an icon to top-level links in every menu:
function change_menu_item_args( $args, $item, $depth ) {
if ( $depth === 0 ) {
$args->link_before = '<span class="dashicons dashicons-admin-links"></span>';
}
return $args;
}
add_filter( 'nav_menu_item_args', 'change_menu_item_args', 10, 3 );
Add icons to menu item links that satisfy all three conditions:
function change_menu_item_args( $args, $item, $depth ) {
if ( $args->theme_location == 'primary' && $item->object == 'page' && $depth === 0 ) {
$args->link_before = '<span class="dashicons dashicons-admin-links"></span>';
}
return $args;
}
add_filter( 'nav_menu_item_args', 'change_menu_item_args', 10, 3 );Changelog
| Since 4.4.0 | Introduced. |
Where the hook is called
nav_menu_item_args
wp-includes/class-walker-nav-menu.php 181
$args = apply_filters( 'nav_menu_item_args', $args, $menu_item, $depth );
