Wordpress: Default sorting by column of custom post type Wordpress: Default sorting by column of custom post type wordpress wordpress

Wordpress: Default sorting by column of custom post type


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


I am a drupal developer and haven't got a chance to play with WordPress. We had the same problem and this is how we fixed it.

Get your custom content type data (either WP default api or custom query), it would be an array of objects. Sort them using below function. return sorted array of posts. Not sure, in which hook you need to implement this in wordpress.

/** *  Function to sort array by key *  sortArrayByKey($yourArray,"name",true); //String sort (ascending order) *  sortArrayByKey($yourArray,"name",true,false); //String sort (descending order) *  sortArrayByKey($yourArray,"id"); //number sort (ascending order) *  sortArrayByKey($yourArray,"count",false,false); //number sort (descending order) */function sortArrayByKey(&$array, $key, $string = false, $asc = true){    if ($string) {        usort($array, function ($a, $b) use (&$key, &$asc) {            if ($asc) return strcmp(strtolower($a{$key}), strtolower($b{$key}));            else        return strcmp(strtolower($b{$key}), strtolower($a{$key}));        });    } else {        usort($array, function ($a, $b) use (&$key, &$asc) {            if ($a[$key] == $b{$key}) {                return 0;            }            if ($asc) return ($a{$key} < $b{$key}) ? -1 : 1;            else     return ($a{$key} > $b{$key}) ? -1 : 1;        });    }}

and then in your hook, you can call this function by

 return $this->sortArrayByKey($posts, "surname");

Function copied from this answer: https://stackoverflow.com/a/39872303/3086531