I have a custom post type called Contact, with custom fields like first name, surname, telephone number etc.
In the admin section they're sorted chronologically I think, but I need them to be sorted by surname by default.
I've read all the other solutions on here and none of them work, including:
function set_post_order_in_admin( $wp_query ) {
global $pagenow;
if ( is_admin() && 'edit.php' == $pagenow && !isset($_GET['orderby'])) {
$wp_query->set( 'orderby', 'surname' );
$wp_query->set( 'order', 'ASC' );
}
}
add_filter('pre_get_posts', 'set_post_order_in_admin' );
But whatever field I try to sort by, nothing changes, except toggling ASC/DESC seems to change to reverse chronological ordering.
What am I doing wrong?
Refer below solutions,
function wpa84258_admin_posts_sort_last_name( $query ){
global $pagenow;
if( is_admin()
&& 'edit.php' == $pagenow
&& !isset( $_GET['orderby'] )
&& !isset( $_GET['post_type'] ) ){
$query->set( 'meta_key', 'last_name' );
$query->set( 'orderby', 'meta_value' );
$query->set( 'order', 'ASC' );
}
}
add_action( 'pre_get_posts', 'wpa84258_admin_posts_sort_last_name' );
OR refer this solution
Replace
$wp_query->set( 'orderby', 'surname' );
$wp_query->set( 'order', 'ASC' );
With
$query->set( 'meta_key', 'surname' ); // name of your post meta key
$query->set( 'orderby', 'meta_value'); // meta_value since it is a string
It may help
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With