Tweaking custom post attribute sortation

I’ve set up a custom field called “Priority” for posts in my WordPress theme. They’re basically integer values that the user can set, which are used in operations elsewhere on the site, and are displayed on the admin posts page. In the edit posts page, the user can set a priority to any integer; if it’s less than or equal to zero, the posts admin page outputs its value instead as N/A (purely visual; the value is still stored and modifiable in the edit post page.) All of these operations work fine.

At this point I’m trying to get sortation on the admin page to work. Priority values are numeric, so meta_value_num seems to work fine. However, because the “N/A” posts are negative, they always end up before or after the numbered posts when I’d rather they be after or before. Also, posts which haven’t had their priority values set yet disappear from the list when I do a priority sort (they reappear when I choose to sort by another criteria, but this is still not ideal.)

How can I wrangle my sorting code to achieve this? The code in its current state is below. I’m also attaching a snippet from our test environment displaying 7 posts after a Priority sort (there are 21 total, but 14 don’t have priority values set and don’t appear).

if ( ! function_exists ( ‘priority_post_column_thinker’ )[![enter image description here][1]][1] {
function priority_post_column_thinker( $query ) {
if ( $query->is_main_query() && ( $orderby = $query->get( ‘orderby’ ) ) ) {
switch( $orderby ) {
case ‘post_priority’:
$query->set( ‘meta_key’, ‘post_priority’ );
$query->set( ‘orderby’, ‘meta_value_num’ );
break;
}
}
}
add_action( ‘pre_get_posts’, ‘priority_post_column_thinker’, 1 );
}

Edit: It would appear that stackexchange won’t let me share my image.

Read more here:: Tweaking custom post attribute sortation

Leave a Reply

Your email address will not be published. Required fields are marked *