Sorting problem with 'query_posts' funcion in wordpress. Sort by custom field not working

wordpress.stackexchange https://wordpress.stackexchange.com/questions/6466

  •  16-10-2019
  •  | 
  •  

Question

0 down vote favorite

Hi, I am working with wordpress where i have a event listing system. There is a custom field in my post called starting_time which is unix timestamp. Now i want to short all posts by starting_time by this query_post command:

query_posts(array(
               'post_type' => 'event',
               'meta_key' => 'end_time',
               'meta_compare' =>'>=',
               'meta_value'=>time(),
               'order_by' => 'start_date',
             'order' => 'ASC'
));

But it not working. Here is the site http://citystir.com/events/. I am echoing the start_time in unix before the time remaining so you can see the value. And also my pagination is not working. May be i did something wrong in the query_post command.

Please someone response.

--------------------- Update -----------------

i have found a wonderful post here kovshenin.com/archives/customize-posts-order-in-wordpress-via-custom-fields but i didn't get it worked. May be for lack of my knowledge. Please take a look at it and let me know if you have any suggestions. I will continue working on that.

-------------------- Resolved -----------------

Changed order_by to orderby. And also i came to know that we can use meta key multiple times if we want it will not conflict. Here is the final code:

$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
query_posts(array(
'post_type' => 'event',
'meta_key' => 'end_time',
'meta_compare' =>'>=',
'meta_value'=>time(),
'meta_key' => 'start_time',
'orderby' => 'meta_value_num',
'post_per_page' => '-1',
'order' => 'ASC',
'paged' => $paged
));

Thanks for all your hard work!

Was it helpful?

Solution

order_by doesn't take a name of the field, it takes type of order. Which for custom numeric field will be orderby=meta_value_num. But actual field used is taken from meta_key and you are already using it for filtering. See Orderby Parameters.

So you can't pull this of this easily at moment, not without filtering and modifying resulting SQL query. Upcoming WP 3.1 will have much more improved and flexible querying support for custom fields and it will likely be easier than.

OTHER TIPS

As for your pagination being broken--when you do a custom query_posts like this, it squashes any vars from the original query. If you want pagination to work, you have to explicitly pass in a "paged" var in the query args. Get the existing paged var like this:

$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;

Then add it to your query args:

'paged' => $paged
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top