Custom Order in WP Query

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.

Read More

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?

Related posts

Leave a Reply

1 comment

  1. Chain the filters:

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

    And in your orderby filter use:

    remove_filter( current_filter(), __FUNCTION__ );