Sort Posts, Pages, Custom Post Types by Date
By default SearchWP sorts results in order of relevance from most relevant to least. Using a SearchWP Mode
we can override the sorting of results to instead return in the order they were published, sorted by most recent to older.
All hooks should be added to your custom SearchWP Customizations Plugin.
<?php | |
// Sort SearchWP Post, Page, and Custom Post Type Results by date in DESC order. | |
add_filter( 'searchwp\query\mods', function( $mods, $query ) { | |
foreach ( $query->get_engine()->get_sources() as $source ) { | |
$flag = 'post' . SEARCHWP_SEPARATOR; | |
if ( 'post.' !== substr( $source->get_name(), 0, strlen( $flag ) ) ) { | |
continue; | |
} | |
$mod = new \SearchWP\Mod( $source ); | |
$mod->order_by( function( $mod ) { | |
return $mod->get_local_table_alias() . '.post_date'; | |
}, 'DESC', 1 ); | |
$mods[] = $mod; | |
} | |
return $mods; | |
}, 20, 2 ); |
Note that this hook applies only to WP_Post
-based Sources (e.g. Posts, Pages, Custom Post Types) but it can be modified to consider any custom Sources you may be using.