[wp-hackers] Global meta_key ordering for a custom post type

Mike Schinkel mikeschinkel at newclarity.net
Fri Aug 27 19:01:17 UTC 2010


If you *always* want to influence the ordering, then I think pre_get_posts might be it. Something like:

add_action('pre_get_posts','custom_priority_orderby');
function custom_priority_orderby($query){
    if(your_criteria()){
       $query->set('meta_key','priority');
       $query->set('orderby','meta_value');
    }
}

Hope this helps.

-Mike

On Aug 27, 2010, at 2:14 PM, Werner wrote:

> Hi Hackers,
> 
> I'm writing a plugin that enables a custom post type for WP3. The post type is for tasks, so I use a meta_key "priority" that I would like to sort the posts by.
> 
> Doing the widget is a snap, I'm using:
> 
>        $r = new WP_Query(
>            array(
>                'post_type'    => 'custom_task_type',
>                'post_status'  => 'publish',
>                'meta_key'     => 'priority',
>                'orderby'      => 'meta_value',
>                'order'        => 'DESC',
>                'meta_compare' => '>=',
>                'meta_value'   => 5,
>                ...
>            )
>        );
>        ...
>        wp_reset_postdata();
> 
> ... to sort the posts for the widget using the "priority" meta_key's value and only accounting for posts with a "priority" meta_value greater than 5.
> 
> *But*... for general post ordering in archive (I also have custom taxonomies) and single page mode (that would also influence things like get_next_post()), I'd like to be able to influence the global loop ordering, using the priority meta_key, for *any* query that involves my custom post type.
> 
> Basically, my custom post type should never be ordered by post date, under any circumstances - always by using the meta_key's value, otherwise the ordering would simply not make any sense.
> 
> What is the best hook to use in my plugin, to influence the ordering of any query that *involves* my custom post type? Should I go the query_posts() route?
> 
> A simple example would mean the world to me at this point.
> 
> Thanks for your time and effort if you have read this far :)
> _______________________________________________
> wp-hackers mailing list
> wp-hackers at lists.automattic.com
> http://lists.automattic.com/mailman/listinfo/wp-hackers



More information about the wp-hackers mailing list