Sorting by date not working - ElasticPress

Hi, I successfully set up Elastic Search and installed the ElasticPress plugin, created the index, and set up the "Search Fields and Weighting" for my custom post type and taxonomy.

My problem is that when a search is made, the posts show up out of chronological order. I'm assuming they are showing up based on the "score" of the search? I tried adding apply_filters( 'ep_set_default_sort', 'date', 'DESC' ); to my functions.php to change the sort order (is that the correct place to put it?) but it did nothing.

What can I do to make my default search show all the latest posts first?

Thanks!!

Asked Sep 29 '21 14:09
avatar shmaltz
shmaltz

3 Answer:

@shmaltz to use filters you'll want to call add_filter with the appropriate arguments and then write a function to return the word "date." Something like

add_filter( 'ep_set_default_sort', 'ep_sort_by_date', 10, 2 );
function ep_sort_by_date( $sort, $order ) {
                                return array(
                    'date' => array(
                        'order' => 'DESC',
                    ),
                );
}

Please note this code is not tested and may contain typos.

1
Answered Dec 07 '20 at 16:14
avatar  of brandwaffle
brandwaffle

As the answer has been answered, and the issue didn't receive any replies for the last month, we are now closing the ticket. If you have any further questions feel free to leave a comment here or open a new issue. Thanks!

1
Answered Jan 22 '21 at 14:32
avatar  of felipeelia
felipeelia

Thank you @brandwaffle for the snippet. Got it working in our setup with a minor tweak (postdategmt instead of date):

add_filter( 'ep_set_default_sort', 'ep_sort_by_date', 10, 2 );
function ep_sort_by_date( $sort, $order ) {
    return array(
        'post_date_gmt' => array(
            'order' => 'DESC',
        ),
    );
}
1
Answered Mar 07 '21 at 19:12
avatar  of binu-mobiux
binu-mobiux