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’));