WP Query Sorting by Custom Field


Hi, When developing themes you might have encountered and requirement to sort the posts by a custom field. Well I got that requirement and this is how I did it,

Need to define ‘meta_key=keyname’ in your WP_query arguments. This is to speficy your custom field.

Then in the ‘order_by’ argument give ‘meta_value’ if its a Alphabetical value or ‘meta_value_num’ if its a numeric value.

Complete query is given below,

$loop = new WP_Query(array(‘post_type’ => ‘doctors’, ‘posts_per_page’ => 10000, ‘meta_key’=>’rank’
, ‘orderby’ => ‘meta_value_num name’, ‘order’ => ‘ASC’));

Advertisements

Let me know what you think .. :)

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s