Last active
July 11, 2019 23:32
-
-
Save dannydickson/a03f51609fd3220f256307d324a50ac3 to your computer and use it in GitHub Desktop.
Sort by custom field in WordPress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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