Skip to content

Instantly share code, notes, and snippets.

@wplit
Last active April 2, 2025 22:35
Show Gist options
  • Save wplit/0efb87d114d9f4dcb03065a888f0a1dc to your computer and use it in GitHub Desktop.
Save wplit/0efb87d114d9f4dcb03065a888f0a1dc to your computer and use it in GitHub Desktop.
auto-populate wpmenu with pages and child pages (code runs on update/save/delete pages)
<?php
function x_auto_populate_menu() {
$menu_id = 123; // Replace with your actual menu ID
if (!$menu_id) {
return; // Exit if no menu ID is set
}
// Get all pages
$pages = get_pages(['sort_column' => 'menu_order']);
// Get current menu items
$menu_items = wp_get_nav_menu_items($menu_id);
$existing_items = [];
if ($menu_items) {
foreach ($menu_items as $item) {
$existing_items[$item->object_id] = $item->ID;
}
}
// Clear existing menu items
if (!empty($existing_items)) {
foreach ($existing_items as $item_id) {
wp_delete_post($item_id, true);
}
}
// Build a list of menu item IDs for parent-child relationships
$menu_item_ids = [];
// Add pages to the menu
foreach ($pages as $page) {
$parent_id = 0;
// Check if the page has a parent
if ($page->post_parent && isset($menu_item_ids[$page->post_parent])) {
$parent_id = $menu_item_ids[$page->post_parent];
}
// Add the page as a menu item
$menu_item_id = wp_update_nav_menu_item($menu_id, 0, [
'menu-item-title' => $page->post_title,
'menu-item-object' => 'page',
'menu-item-object-id' => $page->ID,
'menu-item-type' => 'post_type',
'menu-item-status' => 'publish',
'menu-item-parent-id' => $parent_id,
]);
// Store menu item ID for parent-child mapping
$menu_item_ids[$page->ID] = $menu_item_id;
}
}
// Hook into post save and delete to refresh menu when pages change
function x_trigger_menu_update($post_id) {
// Run only for published pages
if (get_post_type($post_id) === 'page') {
x_auto_populate_menu();
}
}
// Run when a page is added, updated, or deleted
add_action('save_post', 'x_trigger_menu_update');
add_action('delete_post', 'x_trigger_menu_update');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment