Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

Sort by custom fields WordPress

  • REFUNDED

Hi,

need to sort my posts by a custom field. I store a numeric value in the field called SortSalary. It's possible not all of the posts will have this value assigned - those I would like to keep at the end of my results. There are various categories where this needs to work.

I also would like users to be able to change DESC (default order) to ASC.
Any questions please give me a shout.

Thank you,
tomekk


--

I need a code, appreciate your suggestions and links but google offers me the same.

Answers (5)

2010-05-22

Oleg Butuzov answers:

you can change arguments order and order by in your query_posts.
or you can use filter for query or query_order to change your sql.

2010-05-22

Erez S answers:

You may check this:
http://www.dyasonhat.com/wordpress-plugins/smart-sort-wordpress-plugin-sort-posts-by-custom-field/
http://wordpress.org/support/topic/286391 (exactly the same problem as yours)
http://kovshenin.com/archives/customize-posts-order-in-wordpress-via-custom-fields/
Enjoy


Erez S comments:

"users" in his code is the category of the posts that this code will show,so you can remove this:category_name=users in order to show categories from all categories

2010-05-22

Monster Coder answers:

As you want to sort based on custom value, I guess, arguments in get_posts or query_posts may not work. bcoz the field name of post meta table is 'meta_key' which has many different values.

a custom queries may be better solution.

you may also use query_order filter to modify the query.

2010-05-22

Andrzej answers:

What probably would work for you best, would be hooking into the SQL query (hooks like posts_join, posts_where, posts_request), sql-join the custom fields to the posts table and then sort in the relavant way in sql query.

Doing it unfortnately doesn't fit in this questions budget - however you can contact me if you want me to do it? :)


Andrzej comments:

Re: Samuel Arendt; looks like nearly-there but it won't show posts which doesn't have the custom field set?


tomasz kozysa comments:

What is the budget which allows you to post the answer?


Andrzej comments:

just PM'ed you

2010-05-22

Samuel Arendt answers:


<?php
query_posts('meta_key=SortSalary&orderby=SortSalary&order=ASC');
if (have_posts()) : while (have_posts()) : the_post();
the_meta();
endwhile; endif;
wp_reset_query();
?>


or


<?php
query_posts('category_name=users&meta_key=SortSalary&orderby=SortSalary&order=ASC');
if (have_posts()) : while (have_posts()) : the_post();
the_meta();
endwhile; endif;
wp_reset_query();
?>


tomasz kozysa comments:

Almost there? What is users?


Samuel Arendt comments:

<strong>users</strong> is the name of the <strong>category</strong>.