I defined a custom field named crimedate using standard date format Y-m-d
. I defined the filters to make ordering by this date work in the post list of the backend, which works fine.
Now I need the possibility to show posts ordered by anniversary, using only day and month of the crimedate, but I don't know how to do that:
function crimes_columns($columns) {
$columns['crimedate'] = 'Crime date';
$columns['crimeanniversary'] = 'Crime anniversary';
return $columns;
}
add_filter('manage_posts_columns', 'crimes_columns');
function crimes_show_columns($name, $post_id) {
switch ($name) {
case 'crimedate':
// show whole date
echo get_post_meta($post_id, "crimedate", true);
break;
case 'crimeanniversary':
// show only anniversary in format dd/mm
$date = get_post_meta($post_id, "crimedate", false);
echo substr($date,6)."/".substr($date,4,2);
break;
}
return $row_output;
}
add_action('manage_posts_custom_column', 'crimes_show_columns');
add_filter( 'manage_edit-post_sortable_columns', 'crimes_add_custom_column_make_sortable' );
function crimes_add_custom_column_make_sortable( $columns ) {
$columns['crimedate'] = 'crimedate';
$columns['crimeanniversary'] = 'Crime anniversary';
return $columns;
}
add_action( 'pre_get_posts', 'crimes_orderby_meta' );
function crimes_orderby_meta( $query ) {
if(!is_admin())
return;
$orderby = $query->get( 'orderby');
if( 'crimedate' == $orderby ) {
$query->set('meta_key','crimedate');
$query->set('orderby','meta_value');
}
else if( 'crimeanniversary' == $orderby ) {
// ¿¿¿ what to do here ???
}
}
Is it possible to sort dates only by day and month ignoring the year in hook pre_get_posts
? Or do I have to save days and month in two separte fields to make that work?