Instantly share code, notes, and snippets.

Embed
What would you like to do?
Horribly inefficient function to create a menu with all pages as menu items.
<?php
/**
* Insert menu items for all pages.
*
* @package BJ\Menu
* @author bjornjohansen
* @version 0.1.0
* @license https://www.gnu.org/licenses/old-licenses/gpl-2.0.html GNU General Public License version 2 (GPLv2)
*/
/**
* Insert the menu items for the current page and all subpages.
*
* @param int $menu_id The menu we’re inserting the menu items into.
* @param int $parent_page_id The current parent page ID.
* @param int $parent_menu_item_id The current parent menu item ID.
*/
function bj_insert_menuitems( $menu_id, $parent_page_id, $parent_menu_item_id ) {
$page_ids = get_posts( [
'posts_per_page' => 99,
'post_type' => 'page',
'post_parent' => $parent_page_id,
'fields' => 'ids',
] );
foreach ( $page_ids as $page_id ) {
$created_menu_item_id = wp_update_nav_menu_item( $menu_id, 0, [
'menu-item-title' => get_the_title( $page_id ),
'menu-item-object-id' => $page_id,
'menu-item-type' => 'post_type',
'menu-item-object' => 'page',
'menu-item-parent-id' => $parent_menu_item_id,
'menu-item-status' => 'publish',
] );
bj_insert_menuitems( $menu_id, $page_id, $created_menu_item_id );
}
}
/**
* Run the menu item generation.
*/
add_action( 'shutdown', function() {
if ( ! isset( $_GET['generate-menu'] ) ) {
return;
}
// Get the menu if it exists.
$menu_name = 'Main Menu';
$menu_exists = wp_get_nav_menu_object( $menu_name );
// If it doesn't exist, let's create it.
if ( ! $menu_exists ) {
$menu_id = wp_create_nav_menu( $menu_name );
$menu_exists = wp_get_nav_menu_object( $menu_name );
}
// Create the menu items.
bj_insert_menuitems( $menu_exists->term_id, 0, 0 );
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment