Is there any way that i can hard code the custom menu items when first theme installed? I am creating a theme which will automatically make some common pages when installed. So I need to know if I can also add them to WordPress custom menu so client don’t need to add them manually?
In other words: how to insert/create custom menu item programmatically?
Let me know if anything unclear. Guide to the appropriate codex page is welcome. Thanks!
update: tried code from here Targeting specific menu with wp_nav_menu_items
Menu registration:
function register_my_menus() {
register_nav_menus(
array('main-menu' => __( 'Main Menu' ) )
);
}
add_action( 'init', 'register_my_menus' );
Template use:
<?php wp_nav_menu( array( 'theme_location' => 'main-menu' ) ); ?>
Code for adding new items:
function new_nav_menu_items($items) {
if( $args->theme_location == 'main-menu' ){
$homelink = '<li class="home"><a href="' . home_url( '/' ) . '">' . __('Home') . '</a></li>';
$items = $homelink . $items;
return $items;
}
}
add_filter( 'wp_nav_menu_items', 'new_nav_menu_items', 10, 2 );
when adding the code for adding new items in nav menu in functions.php
file nothings happens in menu page in admin panel but the current menu items are gone in site!
The Problem with your code is that its not actually adding the links to the menu and only to the menu’s output, hence the use of a filter (add_filter) so you are just filtering the output of the menu in fact even if you don’t have a menu your link will be shown with the code you are using. But to create a link and add it to a menu you can use this code:
I commented all over to make it simpler.
To create a child page/sub page/second level menu (how ever you may call it), you just need to set the
menu-item-parent-id
in the new item for example:also you can set the position by code with
menu-item-position
and i think its done like this:
Your original code is very close to the money and I seriously think the this long solution by @Bainternet (no offence) is overkill, so have a look at this instead:
Your only problem was that you were not returning $items after the function checked for the correct menu, and you were missing the second callback argument that was needed to make the check ($args).
There’s a bug in WordPress 3.4.2:
https://github.com/WordPress/WordPress/commit/ae96b842f9f55ecfb22da705a4902b9d25580259#wp-includes/nav-menu.php
You need to create the term relation manually:
See https://gist.github.com/4148529 for an example of the Menu class for simple menu creation.
For information, current user has to got rights to add terms, my menu_items were created but not added in the table wp_terms_relationship before I add a call to wp_set_current_user(1);