WordPress Snippets at WPcustoms

Create menu and fill with links

programatically create a navigation menu and pre add custom links with this WordPress code snippet.


/**
 * Snippet Name: Create menu and fill with links
 * Snippet URL: http://www.wpcustoms.net/snippets/create-menu-and-fill-with-links/
 */
 function wpc_pre_add_menus() {
 	register_nav_menus( array( 'main_nav' =--> 'The main menu',)
	);

	$new_menu_id = wp_create_nav_menu('Main Menu');
	$page_args = array(
		'menu-item-object-id' => 1,
		'menu-item-object' => 'page',
		'menu-item-parent-id' => 0,
		'menu-item-type' => 'post_type',
		'menu-item-title' => 'A cool Link Title',
		'menu-item-status' => 'publish',
	);
	if ( $new_menu_id > 0 ) {
		// set our new MENU up at our theme's nav menu location
		set_theme_mod( 'nav_menu_locations' , array( 'main_nav' => $new_menu_id ) );
		// add a menu item to that new menu
		wp_update_nav_menu_item( $new_menu_id , 0, $page_args );
	}
}
add_action( 'init', 'wpc_pre_add_menus' );