No, it’s not possible by using pre_get_posts
alone. But you don’t have to use separate fields for the date.
WP_Query
, although doesn’t provide a simple query arg that would sort the posts by month and day only, you can use the posts_orderby
filter hook to modify the ORDER BY
clause (i.e. ORDER BY <the part here>
) for sorting the posts.
Working Example
-
In the
pre_get_posts
hook, set themeta_key
tocrimedate
:// In crimes_orderby_meta(): elseif ( 'crimeanniversary' == $orderby ) { $query->set( 'meta_key', 'crimedate' ); }
-
Then on the
posts_orderby
hook, you can use theSTR_TO_DATE()
function in MySQL to sort the posts by the month and day of the meta value:Note that I purposely used a static leap year, which means
29/02
(Feb 29th) always comes after28/02
(Feb 28th), when the sort order isASC
.add_filter( 'posts_orderby', 'posts_orderby_crimeanniversary', 10, 2 ); function posts_orderby_crimeanniversary( $orderby, $query ) { if ( is_admin() && 'crimeanniversary' === $query->get( 'orderby' ) ) { global $wpdb; $order = ( 'ASC' === strtoupper( $query->get( 'order' ) ) ) ? 'ASC': 'DESC'; // This means, we still sort by the date, but we "recreate" the date using // the year 2020 (or any leap year), and month and day from the meta value. $orderby = "STR_TO_DATE( CONCAT( '2020-', MONTH( {$wpdb->postmeta}.meta_value ), '-', DAY( {$wpdb->postmeta}.meta_value ) ), '%Y-%m-%d' ) $order"; } return $orderby; }
I hope that helps, and please correct these issues in your code:
-
In
crimes_add_custom_column_make_sortable()
:$columns['crimeanniversary'] = 'crimeanniversary'; // like this $columns['crimeanniversary'] = 'Crime anniversary'; // not this
-
In
crimes_show_columns()
:get_post_meta($post_id, "crimedate", true) // like this get_post_meta($post_id, "crimedate", false) // not this
And just remove that line with
$row_output
— which is not defined. -
And don’t forget the fourth parameter here:
add_action('manage_posts_custom_column', 'crimes_show_columns', 10, 2); // like this add_action('manage_posts_custom_column', 'crimes_show_columns'); // not this!