wp_create_nav_menu()
Creates a new navigation menu in WordPress with the specified name.
The function creates only the menu object itself. Menu items must be added separately via wp_update_nav_menu_item(), and assignment to a theme location must be done separately via the theme settings or set_theme_mod().
The menu name is expected to be already pre-slashed. If the name comes from user input, wp_slash() is typically used before passing it to the function.
The function does not check whether a menu with the same name already exists. If you need to avoid creating duplicates, first check the menu via wp_get_nav_menu_object().
No Hooks.
Returns
Int|WP_Error.
int— ID of the created menu on successful creation.- WP_Error — error object if the menu could not be created.
Usage
wp_create_nav_menu( $menu_name );
- $menu_name(string) (required)
The name of the menu to create.
It is expected that the value is already pre-slashed; if not, use wp_slash().
Examples
#1 Creating a new menu
We create the menu and check whether an error has returned.
$menu_id = wp_create_nav_menu( 'Main menu' );
if ( is_wp_error( $menu_id ) ) {
return;
} #2 Create a menu if it doesn’t already exist
Before creating it, we check whether a menu with this name exists.
$menu_name = 'Main menu';
$menu = wp_get_nav_menu_object( $menu_name );
if ( ! $menu ) {
$menu_id = wp_create_nav_menu( wp_slash( $menu_name ) );
if ( is_wp_error( $menu_id ) ) {
return;
}
} #3 Creating a Menu and Adding a Menu Item
We create a menu, and then add a link to the homepage into it.
$menu_id = wp_create_nav_menu( wp_slash( 'Main menu' ) );
if ( is_wp_error( $menu_id ) ) {
return;
}
wp_update_nav_menu_item( $menu_id, 0, [
'menu-item-title' => __( 'Home', 'textdomain' ),
'menu-item-url' => home_url( '/' ),
'menu-item-status' => 'publish',
] ); #4 Creating a menu and assigning it to the theme area
We create a menu and assign it to the registered location primary.
$menu_id = wp_create_nav_menu( wp_slash( 'Main menu' ) );
if ( is_wp_error( $menu_id ) ) {
return;
}
$locations = get_theme_mod( 'nav_menu_locations', [] );
$locations['primary'] = $menu_id;
set_theme_mod( 'nav_menu_locations', $locations );
Changelog
| Since 3.0.0 | Introduced. |
wp_create_nav_menu() wp create nav menu code WP 7.0
function wp_create_nav_menu( $menu_name ) {
// expected_slashed ($menu_name)
return wp_update_nav_menu_object( 0, array( 'menu-name' => $menu_name ) );
}