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:
1 | function custom_sorting_function_sort_by_number_in_title( $posts_list , $sort_view_id , $orderBy , $query ) |
2 | { |
3 | $list_map = array (); |
4 | foreach ( $posts_list as $object_id ) |
5 | { |
6 | $object = get_post( $object_id ); |
7 | |
8 | //extract the title using a regex |
9 | preg_match( '/\d{4}/' , $object ->post_title, $match ); |
10 | |
11 | if ( $match != FALSE ) |
12 | $list_map [ $object_id ] = $match [0]; |
13 | else |
14 | $list_map [ $object_id ] = '' ; |
15 | } |
16 | |
17 | //sort the dates ascending |
18 | arsort( $list_map , SORT_NUMERIC); |
19 | |
20 | $post_list = array_keys ( $list_map ); |
21 | |
22 | return $post_list ; |
23 | } |