WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm trying to implement my own query ordering, here is what I came up with...

$query = new WP_Query('post_type=contentboxes&include=' . $contentboxes . '&order=ASC&orderby=include' );

My custom loop, $contentboxes looks like 34,45,23,46 with the orderby include argument.

To implement my custom order I use the *pre_get_posts* and *posts_orderby* filter.

function pre_get_posts( $query )
    if ( 'include' == $query->query_vars['orderby'] ) :
        global $order_by_include;
        $order_by_include = TRUE;

*$order_by_include* is a empty variable that is created when my custom ordering is used.

function posts_orderby( $orderby )
    if ( !isset( $order_by_include ) )
        return $orderby;

    global $wpdb, $contentbox_order;

    unset( $order_by_include );
    return "FIND_IN_SET(" . $wpdb->posts . ".ID, '" . $wp_query->query_vars['include'] . "') " . $wp_query->query_vars['order'];

In the posts_orderby filter I'll overwrite the current order to my custom one, if the variable is set. After that I unset the variable to keep the global scope clean and not altering any other loops.

Here is my question now, I don't like using a global variable to implement this feature, I think it is a bit dirty but does the job.

I tried to get the query vars from my custom query inside the posts_orderby which works but my custom.

Is there a cleaner way to do that?

share|improve this question
up vote 2 down vote accepted

Chain the filters:

if ( 'include' == $query->query_vars['orderby'] )
    add_filter( 'posts_orderby', /* … */ );

And in your orderby filter use:

remove_filter( current_filter(), __FUNCTION__ );
share|improve this answer
That is pretty solid and obvious after reading it! Thx Thomas – Horttcore Nov 26 '12 at 14:14
Just for information it is much easier to work with the posts_orderby filter if you accept 2 arguments add_filter( 'posts_orderby', 'function', 10, 2 ); as you are getting the query object as second parameter. – Horttcore Nov 29 '12 at 14:59
@Hottcore, you should add that as a separate answer as it's a much more correct solution than using that hacky chaining – pospi Mar 7 '13 at 7:08

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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