I have a big website with tons of content, and I would like to automatically add all pages and their children to the menu in the backend, so I can then rearrange them easily via drag and drop. I tried to use plugins such as Auto Submenu but it doesn't work, and when I am using it I cannot add any pages manually, as soon as I save they disappear from the menu again. Is there a code I could use in the database to add all pages with their children?

1 Answer 1


The helpers you'll need are wp_create_nav_menu() and wp_update_nav_menu_item().

This will allow you to create a menu and then, using a query posts loop, programmatically add every page in your site dynamically.

You can use the get_pages() helper to retrieve all pages from the DB.

// These are default args and don't need to be set explicitly.
// I've included them here for reference.
$args = array(
    'hierarchical' => 1,
    'post_type' => 'page',
    'post_status' => 'publish'

$pages = get_pages($args);

// loop goes here
// foreach or while will work, whatever you are comfortable with
  • Thank you but that's not what I want, I want to be able use the backend interface, so I can add other links to it in a graphical way, and later non programmers can also rearrange the menu items as needed. I know there is a box called "select all" but it doesn't keep the hierarchy, and you have to do it for every page of the pagination. I would like the same, but for every page of my website while keeping the hierarchy.
    – kali
    Sep 30, 2015 at 17:59
  • Understood. The helpers mentioned in my answer will create the menu programmatically (as you requested). Once your code creates the menu and adds all of the parents and children, you'll be able to freely edit the menu using the backend interface (where you can drag/drop/modify).
    – dswebsme
    Sep 30, 2015 at 18:09
  • oh sorry, thank you :). I'm trying to get all the pages but somehow it just show me some, what can of function should I use? I'm using this now: function get_all_pages(){ $args = array( 'post_type' => 'page' ); $post_query = new WP_Query($args); if($post_query->have_posts() ) { while($post_query->have_posts() ) { $post = $post_query->the_post(); var_dump($post); } } }
    – kali
    Sep 30, 2015 at 18:31
  • I've updated the answer to include a basic usage of the get_pages() helper which you can use to start a loop. In this case my personal preference would be a foreach loop along the lines of <?php foreach ( $pages as $page ) { // add $page to menu here } ?>
    – dswebsme
    Sep 30, 2015 at 19:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.