I defined a custom field named "date" and now want to order the post list in the backend by this field.
I defined the filters to make ordering work and header is clickable and shows the order arrow icon. The problem is that the post list gets ordered by publish date instead of custom field "date".
function crimes_columns($columns) {
$columns['crimedate'] = 'Crime date';
return $columns;
}
add_filter('manage_posts_columns', 'crimes_columns');
function crimes_show_columns($name) {
global $post;
switch ($name) {
case 'crimedate':
echo get_post_meta($post->ID, "date", true);
break;
}
return $row_output;
}
add_action('manage_posts_custom_column', 'crimes_show_columns');
add_filter( 'manage_edit-sortable_columns', 'crimes_add_custom_column_make_sortable' );
function crimes_add_custom_column_make_sortable( $columns ) {
$columns['crimedate'] = 'crimedate';
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','date');
$query->set('meta_type', 'DATE');
$query->set('orderby','meta_value_date');
}
}
Do you think the problem is the name of the field, do I have to rename the field to make it work? Or is there something wrong with my code?
meta_value_date
should bemeta_value
, but why do you need another date field?$query->set('orderby','meta_value');
- and withoutmeta_type
, but without success. To keep it simple I didn't tell that the custom field "date" is defined in a CPT.meta_value
doesn't work for you, but you need to specify the correct meta type for the sorting to works as expected. So what is the format of that meta value, is it like20201013
?mmddYYYY
, e.g.10132020
. So do I have to convert it into a MySQL timestamp with formatY-m-d h:i:s
? How could I do this conversion?YYYY-mm-dd
..