I’ve been working on a big project recently that is based on a listing of green companies that are in specific industries and regions in Norway.
One of the requirements is that certain companies need to listed at the top of a listing of all companies. Since the listings are WordPress posts, the date added, post ID and an alphabetical sort won’t accomplish this. So, I decided to create a simple custom field – companies with one value will be listed higher than ones with another value and then sorted alphabetically.
I wasn’t sure, however, how to sort by the custom field. I located the solution in the WordPress forums and learned that this can be done with a post query that includes the name of the custom field and sort by the custom field’s value in the arguments of the query.
The query would look like this:
<?php $saved = $wp_query; query_posts( 'showposts=1000&meta_key=popularity&orderby=meta_value&order=ASC' ); ?> <?php if ( have_posts() ) { while ( have_posts() ) { the_post(); ?>
- showposts=1000 is how many posts that you would like to display. 1000 seems high but I am only displaying the title, which is the company name, and I want all of them to be listed.
- meta_key=popularity – this is the name of the custom field that you created and by which you want to sort the posts.
- orderby=meta_value – this is saying to sort the posts by the custom field you listed under meta_key
- order=ASC – this is just saying use an ascending order for the sort
If you want to learn more about using custom fields, Jeff Starr has a great tutorial at Perishable Press. It’s a couple of years old now but is still the one of the clearest out there.
I tend to not use Custom Fields, if possible, because I find that many clients find them a bit confusing. This issue can be resolved, however, by using the Advanced Custom Fields plugin. It makes it really easy to create a block in the editor, which can be called something like Company, and all of the fields are listed for input in this block. The plugin can also add the visual editor to specific fields and a simple image uploader. When this plugin is used, custom fields are no longer confusing, and become additional fields to use when creating a new post.
The plugin will create a nice custom field area that looks like the following.
Do you use any custom fields? Does your theme use custom fields for images, slideshows or other features? Have you ever needed to sort by a custom field?
photo credit: mr_t_in_dc
Jennifer says
Actually I think showposts is technically deprecated. You can get the same effect by using “posts_per_page” instead – and setting the value to -1 (which would get all posts) :D
Kim Woodbridge says
Thanks Jennifer! It’s been my month for deprecated code ;-)
Lily Rose says
I’ve used it before but it never crossed my mind to sort anything by that field.