6

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?

1

2 Answers 2

10

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);
3
  • Best solution so far. This requires PHP 5.3 though!?
    – Xaver
    Commented Jul 3, 2015 at 12:13
  • 1
    @revaxarts yes. Use a named function instead of a anonymous function for 5.2 compat. But... really?
    – gmazzap
    Commented Jul 3, 2015 at 12:16
  • yes, really ;) thx!
    – Xaver
    Commented Jul 3, 2015 at 12:17
1
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.