In case it saves anyone else the time, adding the following filter on pre_get_posts
as an admin only code snippet got this working for me.
add_action( 'pre_get_posts', 'my_sort_admin_column' );
function my_sort_admin_column( $query ) {
/**
* We only want our code to run in the main WP query
* AND if an orderby query variable is designated.
*/
if ( $query->is_main_query() && ( $orderby = $query->get( 'orderby' ) ) ) {
switch( $orderby ) {
// If we're ordering by 'shared_counts_total'
case 'shared_counts':
// Setting just <code>meta_key</code> is not sufficient, as this
// will ignore posts that do not yet, or never will have
// a value for the specified key. This meta query will
// register the <code>meta_key</code> for ordering, but will not
// ignore those posts without a value for this key.
$query->set( 'meta_query', array(
'relation' => 'OR',
array(
'key' => 'shared_counts_total',
'compare' => 'NOT EXISTS'
),
array(
'key' => 'shared_counts_total',
'compare' => 'EXISTS'
),
) );
// Order by the meta value, then by the date if multiple
// posts share the same value for the provided meta key.
// Use <code>meta_value_num</code> since the meta value
// for shared_counts are numeric.
$query->set( 'orderby', 'meta_value_num date' );
break;
}
}
}
The nice function using ‘switch’ comes from wpdreamer and was helpful since I had columns from another plugin with the same issue. This answer on stackexchange provided the solution for getting the posts without a shared_count_total to show.
-
This reply was modified 4 years, 2 months ago by
sloweye. Reason: corrections to comments in code
-
This reply was modified 4 years, 2 months ago by
sloweye.
-
This reply was modified 4 years, 2 months ago by
sloweye.
Thanks for the message. I just tried implementing this in Shared Counts but it didn’t work as expected. The zero count posts did remain, but they appear in the wrong order.
When sorting in DESC order (largest at top) it goes zero count posts, high count posts, low count posts: https://cl.ly/688079b025df
When sorting in ASC order (smallest at top) it goes low count posts, high count posts, zero count posts: https://cl.ly/d9c279abd826
To implement this change, I modified the sort_column_query() method like so: https://gist.github.com/billerickson/6463e9660211e056ad3e657c2082f94c
I don’t know why, but the order worked better for me if the ‘NOT EXISTS’ array is before the ‘EXISTS’ array.
-
This reply was modified 3 years, 9 months ago by
sloweye. Reason: typo
Here’s a more recent answer in the stackexchange thread I linked to earlier that has more about the order of the meta queries: https://wordpress.stackexchange.com/a/329687/144711
Wow you’re right, I didn’t realize the order would have that effect.
Thank you! I’ll get this added to Shared Counts for the next release.