Forums Forums Search & Filter Pro Search results sort order by custom field value

Tagged: 

Viewing 5 posts - 1 through 5 (of 5 total)
  • Anonymous
    #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
    #180784

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

    Anonymous
    #180788

    Hmm … I don’t think that actually works. Any help is appreciated.

    Trevor
    #180809

    You 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

    Anonymous
    #180817

    Not sure how I missed that! Thanks so much!

Viewing 5 posts - 1 through 5 (of 5 total)