How to output Natural order for items along with Automatic Order

Share on FacebookTweet about this on TwitterShare on Google+Share on LinkedInPrint this page

At the code level there are multiple type of order types, meaning the results can be different depending on the algorithm is being applied. As default a text sorting (SORT_REGULAR flag) is being used.

Presuming we have the following title list:

  • Title 1
  • Title 21
  • Title 22
  • Title 3

When using a default sorting by Title, the objects are outputted in the above order, which is the default.
However sometime a natural sort is required to apply (SORT_NATURAL flag), so the output will be the following:

  • 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
Notify of
guest
0 Comments
Inline Feedbacks
View all comments