How to output Natural order for items along with Automatic Order
Dive into the intricacies of sorting at the code level, where various order types come into play, influencing the results based on the algorithm applied. By default, a text sorting mechanism (utilizing the SORT_REGULAR flag) is employed.
Presuming we have the following title list:
- Title 1
- Title 21
- Title 22
- Title 3
When sorted by Title using the default method, the objects are outputted in the above order.
However, there are instances where a natural sort is required (using the SORT_NATURAL flag), resulting in the following order:
- Title 1
- Title 3
- Title 21
- Title 22
This can be achieved through Automatic Order along with a Custom Function callback. The following code can be used:
function custom_sort_function( $post_list, $sort_view_id, $orderBy, $query ) { if ( count($post_list) < 1 ) return $post_list; //retrieve the title of objects $objects_map = array(); foreach($post_list as $post_id ) { $post_data = get_post( $post_id ); $objects_map[$post_id] = $post_data->post_title; } //apply natural sorting natsort( $objects_map ); $post_list = array_keys( $objects_map ); return $post_list; }
Then the custom_sort_function can be used along the Custom Function entry field.
Subscribe
Login
0 Comments
Inline Feedbacks
View all comments