Question

I'm using get_posts() like this:

$posts = get_posts(array('orderby' => 'post_status'))

which is not possible cause it's not in the allowed keys in the parse_orderby() method

How to get around this limitation?

Was it helpful?

Solution

You can use 'posts_orderby' filter to change the SQL performed.

Note that:

  • using get_posts() you need to set 'suppress_filters' argument of false for the filter to be performed
  • if you don't explicitly set 'post_status' you'll get only published posts (so no much to order)

Code sample:

$filter = function() {
  return 'post_status ASC';
};

add_filter('posts_orderby', $filter);

$posts = get_posts('post_status' => 'any', 'suppress_filters' => false);

remove_filter('posts_orderby', $filter);

OTHER TIPS

add_filter('posts_orderby', 'custom_post_status', 10,2);
function custom_post_status($args, $wp_query){
  if($wp_query->query_vars['orderby'] == 'post_status') {
    if($wp_query->query_vars['order']) {
        return 'post_status '.$wp_query->query_vars['order'];
    }
    else {
        return 'post_status ASC';
    }
  }
  return $args;
} 

Adding this would enable 'orderby' => 'post_status' in WP_Query

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top