WordPress uses the
menu_order column in the posts table to manage the ordering of pages and hierarchical post types. If you have a situation where you need to display a collection of posts in a particular order, making use of this database column is the way to go. Then whether you are fetching posts with
get_posts() or creating custom queries with
WP_Query, all you need to do is pass
'menu_order post_title' as your
Oftentimes, the next step is to allow users to easily change the display order. I really like to make it easy on users, so I use the built-in jQuery Sortable interaction to allow drag and drop reordering. Regardless of how you choose to allow reordering, you will have to update the
menu_order value in the database for multiple posts.
Since I use AJAX to pass an array of ordered post IDs, performance is really important. So, I set out to find a way to reorder a collection of posts using a single MySQL query and this is what I came up with:
To use this function, all you have to do is pass in an ordered array of numeric post IDs. The function will take the post IDs in the order they appear in the array and update the
menu_order value in the database for each post.