pre_wp_nav_menu
Allows you to change the output of wp_nav_menu() at an early stage, before the function's main code runs.
Before the menu is generated, the filter can stop wp_nav_menu() from running or supply already generated HTML that is immediately displayed or returned, depending on the $args->echo parameter.
Usage
add_filter( 'pre_wp_nav_menu', 'wp_kama_pre_wp_nav_menu_filter', 10, 2 );
/**
* Function for `pre_wp_nav_menu` filter-hook.
*
* @param string|null $output Nav menu output to short-circuit with.
* @param stdClass $args An object containing wp_nav_menu() arguments.
*
* @return string|null
*/
function wp_kama_pre_wp_nav_menu_filter( $output, $args ){
// filter...
return $output;
}
- $output(string/null)
Value that determines how
wp_nav_menu()proceeds.- If
null, execution continues. - If the value is not
null, the rest of the code is skipped and the supplied value is returned. Ifecho = truewas specified, the result is displayed.
Default: null
- If
- $args(stdClass)
- Object containing the arguments passed to
wp_nav_menu(), merged with the defaults.
Examples
#1 Display an additional menu for logged-in users
This example assumes there are two menu locations: header-menu and header-menu-user-logged. Logged-out users see the menu assigned to header-menu; logged-in users additionally see the menu assigned to menu-user-logged.
// In header.php
wp_nav_menu( [
'theme_location' => 'header-menu',
] );
// In functions.php
add_action( 'after_setup_theme', 'dev_menu_setup' );
function dev_menu_setup() {
register_nav_menus( [
'header-menu' => 'Top menu',
'menu-user-logged' => 'Top menu for logged-in users',
] );
}
add_filter( 'pre_wp_nav_menu', 'change_pre_wp_nav_menu', 10, 2 );
function change_pre_wp_nav_menu( $output, $args ) {
if ( $args->theme_location === 'header-menu' && is_user_logged_in() ) {
wp_nav_menu( [
'theme_location' => 'menu-user-logged',
] );
}
return $output;
}Changelog
| Since 3.9.0 | Introduced. |
Where the hook is called
pre_wp_nav_menu
wp-includes/nav-menu-template.php 118
$nav_menu = apply_filters( 'pre_wp_nav_menu', null, $args );