0

I have a function that creates custom admin menu items from an array of child pages.

They seem to get returned in alpha-numeric order.

I would like them to get sorted by the page order set in page attributes.

I have searched online, but can't seem to find an easy solution. Before writing a script to do this manually I was wanting to see if anyone has some input on a wp_core method that might make this easier.

Here is the current code for reference:

public function create_custom_menu() {
    $menuArray = $this->get_top_level_pages();
        foreach ($menuArray as $key => $value) {
            add_menu_page( 
                $value->post_title, 
                $value->post_title, 
                'manage_options', 
                $value->post_name.'-admin-page', 
                array( $this, 'create_admin_page'), 
                'dashicons-admin-home' ,
                6
            );
      }
}
0

Ok it took me a while, but I think I have it. I had to use usort. I also included the code for the get_top_level_pages() method.

    $my_wp_query = new WP_Query();
    $all_wp_pages = $my_wp_query->query(array('post_type' => 'page', 'posts_per_page' => '-1'));
    $top_level_pages =  get_page_by_title('Locations');
    $menuArray = get_page_children( $top_level_pages->ID, $all_wp_pages );
    function compareOrder($a, $b) {
        return $a->menu_order - $b->menu_order;
    }
    usort($menuArray, 'compareOrder');

or, as I found out later I could just replace the last value in my array with:

public function create_custom_menu() {
    $menuArray = $this->get_top_level_pages();
        foreach ($menuArray as $key => $value) {
            add_menu_page( 
                $value->post_title, 
                $value->post_title, 
                'manage_options', 
                $value->post_name.'-admin-page', 
                array( $this, 'create_admin_page'), 
                'dashicons-admin-home' ,
                $value->page_attributes->menu-order
            );
      }
}

or even easier, I could have just added 'orderby'=>'menu_order' to my query initially.

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.