Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Sort by custom field in WordPress
// Taken and modified from
// Put here for posterity's sake as a bookmark of sorts
// Allows sorting by custom field value instead of default.
// This will allow client to be able to set the order of these goals/landing pages as they add more.
// Can be added to functions.php, or to custom template that gets called before your custom loop.
function my_pre_get_posts( $query ) {
// do not modify queries in the admin
if( is_admin() ) {
return $query;
// only modify queries for 'goals' post type (edit for your own post type)
if( isset($query->query_vars['post_type']) && $query->query_vars['post_type'] == 'goals' ) {
$query->set('orderby', 'meta_value');
$query->set('meta_key', 'goal_order_in_list'); // Set the meta_key to match the ACF "Field Name" (in this case goal_order_in_list)
$query->set('order', 'ASC');
// return
return $query;
add_action('pre_get_posts', 'my_pre_get_posts');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.