Set wordpress post order in admin screen based on meta value

In working with a client who had a number of static posts that were named according to a set naming convention.  By default of course WordPress orders posts by the date of post so that you always see the most recent post even in the admin area.  However, the client wanted to set wordpress post order in admin screen based on meta value not by the default most recent post.  The meta values were something similar to 000, 001, 002, 003, and so on.
There were a few helpful blog posts out there setting the admin post order based on simply the title.  These were helpful in getting a start, however, we needed the sort order based on the meta value.  Also, if you attempt to set the post order in the admin section based on a meta value without any checks, this will also affect your view of pages as well as even media, as we found out.  Before putting a check in our code, when navigating to pages, and media, we showed to have items there, but it gave us the generic, there are no items to view message.  So we effectively tanked viewing of pages and media inadvertently.
The below code however, checks to make sure the order is set in admin as well as is only set on post items which solves the issue above we were seeing with our pages and media disappearing:
function set_admin_posts_meta( $wp_query )
{    if ( is_admin()) { 
$post_type = $wp_query->query['post_type'];
if ( $post_type == 'post')
{   $wp_query->set( 'orderby', 'meta_value'); 
$wp_query->set( 'meta_key', 'orderkey'); 
$wp_query->set( 'order', 'ASC');  
     } 
   }
 
add_filter('pre_get_posts', 'set_admin_posts_meta' );
The first “if” statement of course checks to see if we are in the admin section.  Then the $wp_query->query[‘post_type’]; section checks to see what type of post type we are dealing with.  The second “if” statement checks to see if the returned post_type is of type ‘post’ and then proceeds to set the order of the posts based on the meta_value called orderkey and sorts those in ASC order.
As expected, the code above properly sets the sort order based on meta_value and also does not affect the pages admin screen or the media screen.

Post a Comment

0 Comments