I\'ve set up a custom post type called clientarea, and set up several custom columns for it in the admin area - the custom columns are all custom meta fields, as you can see
The problem is that you run the clientarea_default_order
callback too late.
To fix that you only have to change the priority from the default one that's 10
:
add_action( 'pre_get_posts','clientarea_default_order');
to the priority of 9
:
add_action( 'pre_get_posts','clientarea_default_order', 9 );
But you don't actually need two pre_get_posts
callbacks.
You can combine them:
is_admin() && add_action( 'pre_get_posts', 'extranet_orderby' );
function extranet_orderby( $query )
{
// Nothing to do:
if( ! $query->is_main_query() || 'clientarea' != $query->get( 'post_type' ) )
return;
//-------------------------------------------
// Modify the 'orderby' and 'meta_key' parts
//-------------------------------------------
$orderby = $query->get( 'orderby');
switch ( $orderby )
{
case 'extranet_sort_office':
$query->set( 'meta_key', 'extranet_case_office' );
$query->set( 'orderby', 'meta_value_num' );
break;
case 'extranet_sort_date':
$query->set( 'meta_key', 'extranet_appointment_date' );
$query->set( 'orderby', 'meta_value' );
break;
case '': // <-- The default empty case
$query->set( 'meta_key', 'extranet_appointment_date' );
$query->set( 'orderby', 'meta_value' );
break;
case 'extranet_sort_type':
$query->set( 'meta_key', 'extranet_appointment_type' );
$query->set( 'orderby', 'meta_value' );
break;
case 'extranet_sort_IP':
$query->set( 'meta_key', 'extranet_insolvency_practioner' );
$query->set( 'orderby', 'meta_value_num' );
break;
default:
break;
}
}
where we added a main query check and an empty switch case.
Here's another approach, without the switch
part (PHP 5.4+):
is_admin() && add_action( 'pre_get_posts', 'extranet_orderby' );
function extranet_orderby( $query )
{
// Nothing to do
if( ! $query->is_main_query() || 'clientarea' != $query->get( 'post_type' ) )
return;
//-------------------------------------------
// Modify the 'orderby' and 'meta_key' parts
//-------------------------------------------
$orderby = strtolower( $query->get( 'orderby') );
$mods = [
'office' => [ 'meta_key' => 'extranet_sort_office', 'orderby' => 'meta_value_num' ],
'date' => [ 'meta_key' => 'extranet_appointment_date', 'orderby' => 'meta_value' ],
'' => [ 'meta_key' => 'extranet_appointment_date', 'orderby' => 'meta_value' ],
'type' => [ 'meta_key' => 'extranet_sort_type', 'orderby' => 'meta_value_num' ],
'ip' => [ 'meta_key' => 'extranet_insolvency_practioner', 'orderby' => 'meta_value_num' ],
];
$key = 'extranet_sort_' . $orderby;
if( isset( $mods[$key] ) )
{
$query->set( 'meta_key', $mods[$key]['meta_key'] );
$query->set( 'orderby', $mods[$key]['orderby'] );
}
}