Skip to content

Instantly share code, notes, and snippets.

@bookchiq
Last active April 28, 2021 17:20
Show Gist options
  • Save bookchiq/119686e7d5aaac4c3e1ae0fc2cfbcaa5 to your computer and use it in GitHub Desktop.
Save bookchiq/119686e7d5aaac4c3e1ae0fc2cfbcaa5 to your computer and use it in GitHub Desktop.
One-time autogenerate a menu from WordPress page structure
<?php
/**
* Generate a menu with content and hierarchy that match the page structure.
* Trigger with ?autogenerate=true in the URL; note that it won't update a menu, so you'll need to delete and recreate if necessary.
*
* @return void
*/
function yoko_child_theme_create_menu_from_page_structure() {
$menu_name = 'Auto-generated menu from page structure';
$post_type = 'page';
if (
! empty( $_GET['autogenerate'] ) &&
'true' === $_GET['autogenerate']
) {
// Does the menu exist already? We don't want to overwrite a 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 );
$pages_to_add = get_posts(
array(
'numberposts' => -1,
'orderby' => 'menu_order',
'order' => 'ASC',
'post_type' => $post_type,
)
);
if ( ! empty( $pages_to_add ) ) {
// We have to loop through them somewhat carefully to ensure that the parents are created before their children.
$valid_parent_ids = array( 0 );
$new_menu_obj = array();
do {
$skipped_pages = 0;
foreach ( $pages_to_add as $index => $page_to_add ) {
if ( in_array( $page_to_add->post_parent, $valid_parent_ids, true ) ) {
$new_menu_obj[ $page_to_add->ID ] = array();
$new_menu_obj[ $page_to_add->ID ]['menu-item'] = wp_update_nav_menu_item(
$menu_id,
0,
array(
'menu-item-title' => $page_to_add->post_title,
'menu-item-object' => $post_type,
'menu-item-parent-id' => $new_menu_obj[ $page_to_add->post_parent ]['menu-item'],
'menu-item-object-id' => $page_to_add->ID,
'menu-item-type' => 'post_type',
'menu-item-status' => 'publish',
)
);
if (
empty( $new_menu_obj[ $page_to_add->post_parent ]['menu-item'] ) &&
! empty( $page_to_add->post_parent )
) {
$test_array = array(
'menu-item-title' => $page_to_add->post_title,
'menu-item-parent-id' => $new_menu_obj[ $page_to_add->post_parent ]['menu-item'],
'post-parent' => $page_to_add->post_parent,
'menu-item-object-id' => $page_to_add->ID,
);
}
$valid_parent_ids[] = $page_to_add->ID;
unset( $pages_to_add[ $index ] );
} else {
$skipped_pages++;
}
}
} while ( 0 < $skipped_pages );
}
}
}
}
add_action( 'wp', 'yoko_child_theme_create_menu_from_page_structure' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment