Skip to content

Instantly share code, notes, and snippets.

@jbjanot
Created April 26, 2014 16:32
Show Gist options
  • Save jbjanot/11324611 to your computer and use it in GitHub Desktop.
Save jbjanot/11324611 to your computer and use it in GitHub Desktop.
WordPress menu on the fly
<?php
// it needs to be attached to a hook like save_post or something similar
$pages = get_posts(
array(
'post_type' => 'page',
'posts_per_page' => - 1
)
);
$projects = get_posts(
array(
'post_type' => 'project',
'posts_per_page' => - 1
)
);
$menu_name = 'ms-main-menu';
$menu_exists = wp_get_nav_menu_object( $menu_name );
if ( $menu_exists ) {
wp_delete_nav_menu( $menu_name );
}
$menu_id = wp_create_nav_menu( $menu_name );
$menu = get_term_by( 'name', $menu_name, 'nav_menu' );
// Set up default page items
if ( ! empty( $pages ) ) {
foreach ( $pages as $page ) {
$itemData = array(
'menu-item-object-id' => $page->ID,
'menu-item-object' => $page->post_type,
'menu-item-type' => 'post_type',
'menu-item-status' => 'publish'
);
wp_update_nav_menu_item($menu->term_id, 0, $itemData);
}
}
// Set up default project items
if ( ! empty( $projects ) ) {
foreach ( $projects as $project ) {
$itemData = array(
'menu-item-object-id' => $project->ID,
'menu-item-object' => $project->post_type,
'menu-item-type' => 'post_type',
'menu-item-status' => 'publish'
);
wp_update_nav_menu_item($menu->term_id, 0, $itemData);
}
}
$locations = get_theme_mod('nav_menu_locations');
$locations['main'] = $menu->term_id;
set_theme_mod( 'nav_menu_locations', $locations );
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment