Im automatically creating pages with the below code, after that I create a custom menu and insert all the pages to this menu.

$create_pages = array('Home', 'About', 'Contact'); // there will be more items
$count = 1; 
foreach ($create_pages as $new_page) {
    $add_pages = array(
        'post_title' => $new_page,
        'post_content' => '',
        'post_status' => 'publish',
        'post_type' => 'page',
        'menu_order' => $count++ // incrementing the order value to overwrite default alphabetical ordering
    $page_id = wp_insert_post($add_pages);

So far I managed to actually overwrite the default alphabetical ordering and now on the Pages screen, all the pages are ordered the way I want.

$main_nav_id = wp_create_nav_menu('Main menu', array('slug' => 'main-nav'));
set_theme_mod('nav_menu_locations', array('main-nav' => $main_nav_id));

$pages = get_pages();
$count = 1; 
foreach($pages as $page) {
    $item = array(
        'menu-item-object-id' => $page->ID,
        'menu-item-object' => 'page',
        'menu-item-type' => 'post_type',
        'menu-item-status' => 'publish',
        'menu-item-position' => $count++ // im trying to use the same approach
    wp_update_nav_menu_item($main_nav_id, 0, $item);

So with this code, Im trying to use the same approach as I did before with the pages, but whatever I try, the menu items are still ordered in a weird way, I just want them to be ordered the same way as they are ordered on the Pages screen. How could I fix this?

1 Answer 1


You don't set sort_column to menu_order when you call get_pages, so it defaults to sorting on post_title.

$pages = get_pages( array( 'sort_column' => 'menu_order' ) );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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