Forums › Forums › Search & Filter Pro › Search results sort order by custom field value
Tagged: sort
- This topic has 4 replies, 2 voices, and was last updated 6 years, 10 months ago by
Anonymous.
-
Anonymous(Private) June 20, 2018 at 2:47 pm #180783
Hi, I’ve been looking in the forum for a function to sort search results by a custom field value without any luck. The only ones I’ve found that might work are all private, so I’m hoping someone can assist me. I have a custom field with a date (ie. 01/01/2019 ) that I would like to sort ASC for search results.
Thank you in advance.
Site address: https://www.suncoastlifelonglearning.org/Anonymous(Private) June 20, 2018 at 2:52 pm #180784I’ve found my answer for anyone looking
(https://wordpress.stackexchange.com/questions/204546/sort-search-results-by-custom-field) …// sort by custom field
add_action( ‘pre_get_posts’, function ( $q )
{
if ( !is_admin() // Target only front end queries
&& $q->is_main_query() // Target the main query only
&& ( $q->is_search() )
) {
$q->set( ‘meta_key’, ‘Starts from’ );
$q->set( ‘order’, ‘ASC’ );
$q->set( ‘orderby’, ‘meta_value’ );
}
});Trevor(Private) June 20, 2018 at 4:23 pm #180809You SHOULD be able to do this in the form
Posts
settings tab. A couple of gotchas though:#1 If you sort by any field, if a post has no value for that field, that post disappears from the results.
#2 The dates must be stored in the database in the form YYYYMMDD -
AuthorPosts