Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress: Default sorting by column of custom post type

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?

like image 248
Sean H Avatar asked Aug 02 '16 13:08

Sean H


2 Answers

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

like image 59
Gnanasekaran Loganathan Avatar answered Nov 16 '22 01:11

Gnanasekaran Loganathan


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

like image 25
Sanjay Avatar answered Nov 16 '22 01:11

Sanjay