2

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;
    endif;
}

*$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?

1 Answer 1

3

Chain the filters:

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

And in your orderby filter use:

remove_filter( current_filter(), __FUNCTION__ );
3
  • That is pretty solid and obvious after reading it! Thx Thomas
    – Horttcore
    Commented Nov 26, 2012 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
    Commented Nov 29, 2012 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
    Commented Mar 7, 2013 at 7:08

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.