How to sort posts automatically by a number/year included in title

Manual sorting is a fun process, order adjustments are easy through the Advanced Post Types Order plugin drag & drop interface. Automatisation is possible through Automatic Order functionality. This provides a powerful set-up for creating algorithmic based sorting without a human intervention. For large list, this might be a good option to save good time spent on manual sorting adjustments.

For some sites, the post title ( or any other post data like content, excerpt etc ) might contain important information on which a sort is required to apply. For example a year number can be included in the title e.g.:
– Canada 1978 edition
– Spain 2000 issues
– Early Belgium 2003 fabric
– Bohemia and Moravia 1944 history

Sorting ascending by the year in titles can be done manually, however automatisation is easy achievable through Custom Function Callback and a bit of code.

 

In this particular example the callback function name is called “custom_sorting_function_sort_by_number_in_title”. The function should be included within theme functions.php or a custom plugin:

function custom_sorting_function_sort_by_number_in_title( $posts_list, $sort_view_id, $orderBy, $query)
        {
            $list_map   =   array();
            foreach($posts_list  as  $object_id)
                {
                    $object =   get_post($object_id);
                    
		    //extract the title using a regex	
                    preg_match('/\d{4}/', $object->post_title, $match );
                    
                    if ( $match  != FALSE )
                        $list_map[$object_id]   =   $match[0];    
                        else
                        $list_map[$object_id]   =   '';
                }
                 
            //sort the dates ascending
            arsort($list_map, SORT_NUMERIC);
             
            $post_list  =   array_keys($list_map);
                 
            return $post_list;  
        }