Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordering Wordpress posts with meta values

Tags:

wordpress

I have this code below that basically creates 4 links to allow me to sort posts on the front end.

        <div class="sort">
            Sort projects by:
            <a href="http://mydomain.com/find-work/" >Latest Projects</a>
            <a href="http://mydomain.com/find-work/?order=asc&orderby=date" >Ending Soon</a>
            <a href="http://mydomain.com/find-work/?order=asc&orderby=meta_value_num&meta_key=proj_budget" >Budget Low</a>
            <a href="http://mydomain.com/find-work/?order=desc&orderby=meta_value_num&meta_key=proj_budget" >Budget High</a>
        </div>

        <?php   $my_query = new WP_Query( array( 
                        'post_type' => 'project',
                        'orderby' => get_query_var('orderby'),
                        'order' => get_query_var('order'),
                        ));      
                while ( $my_query->have_posts() ) : $my_query->the_post(); ?>

The second link, ordering by date works fine but the two links to order by meta values is not working. I am obviously missing something in my query but for the life of me can't work it out.

Any ideas??

like image 863
user537137 Avatar asked Dec 05 '22 15:12

user537137


2 Answers

It's a bit magical with meta values:

$my_query = new WP_Query( array( 
                    // 'post_type' => 'project',
                    'meta_key' => 'proj_budget',
                    'orderby' => 'meta_value_num'
                    ));      

All the possible values are explained in codex: http://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters

like image 163
Jure C. Avatar answered Dec 27 '22 04:12

Jure C.


It's quite simple:

new WP_Query( array( 
              //I used meta_value_num below, because it's about a numeric field
              //if you don't have a numeric field, just use meta_value
              "orderby" => 'meta_value_num',
              "meta_key" => 'price',
              "order" => 'DESC'
              ));
like image 20
Erik van de Ven Avatar answered Dec 27 '22 04:12

Erik van de Ven