EDIT: I can't delete my question because of the open bounty, but it looks like the problem is caused by the "Post Types Order" plugin I have installed. I have it set to not order news
post types, but for some reason it's still adding its sorting to the main query. It's my mistake, you should always disable plugins when debugging issues.
I'm trying to set the default sorting on a column for my custom post type news
. The column sorts fine when the heading is clicked on, but when you first visit the post listing it will only sort by the default sorting (published date). Here's my pre_get_posts
action:
add_action( 'pre_get_posts', function( $query ) {
global $pagenow;
if ( !is_admin() || $pagenow !== 'edit.php' )
return;
$post_type = $query->get( 'post_type' );
$order_by = $query->get( 'orderby' );
if ( $post_type == 'news' ) {
if ( empty( $order_by ) )
$order_by = 'news-date';
switch ( $order_by ) {
case 'news-date':
$query->set( 'meta_key', 'date' );
$query->set( 'orderby', 'meta_value_num' );
break;
}
}
} );
After sorting manually by clicking the heading the URL becomes edit.php?post_type=news&orderby=news-date&order=asc
so I'm sure all my parameters match up.
I tried adding a var_dump( $query );
in the switch statement after setting the query and the query includes the updated meta_key
and orderby
values, so I'm assuming the query is being modified correctly, but still it's doing the default sorting.
I thought maybe the date
meta key was already used for some reason (maybe by a plugin) so I checked the wp_postmeta
table in the database but the only meta keys named date
were the values set with the ACF Date Picker, so everything is fine there.
Hopefully it's just something stupid I'm missing.