Skip to content

Instantly share code, notes, and snippets.

@dannydickson
Last active July 11, 2019 23:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dannydickson/a03f51609fd3220f256307d324a50ac3 to your computer and use it in GitHub Desktop.
Save dannydickson/a03f51609fd3220f256307d324a50ac3 to your computer and use it in GitHub Desktop.
Sort by custom field in WordPress
<?php
// Taken and modified from https://www.advancedcustomfields.com/resources/orde-posts-by-custom-fields/
// 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