How do I prioritize posts over pages in a wordpress/genesis search result page? Similar to this code, except I'd like posts to show before pages and I can't seem to fully adjust this code to do it:
function change_search_result_order($query) {
// Check if current page is search page
if ($query->is_search) {
// Specify orderby and order, ordering will be by slug of post_type: pAge > pOst
$query->set('orderby', 'post_type');
$query->set('order', 'ASC');
};
return $query;
}
add_filter('pre_get_posts', 'change_search_result_order');
this code block was also mentioned, but I can't seem to find where it fits--if I could, would it be as simple as switching page and post?
$query->set('post_type', array('page','post'));
Original source: How to prioritize pages over posts when searching?
thanks in advance! Adam
If you break down the code that was given in that other answer, you can clearly see what it's doing.
pre_get_posts
, which is before any posts are fetched.search
query, and won't fire on other pages or page templates.post_types
to page
and post
, thereby removing any custom post types.post_type
Add the post_types
in there, so that way if you use another plugin that adds CPTs or add your own, they won't be included (such as events or staff members).
Since WP 4.0 the $query
accepts type
as an orderby
parameter. Note that post_type
works as well, but the default non-aliased value is type
.
Change the order to Desc
since you want [PO]sts before [PA]ges
add_filter( 'pre_get_posts', 'change_search_result_order' );
function change_search_result_order($query){
if( $query->is_search ){
$query->set( 'post_type', array( 'page', 'post' ) );
$query->set( 'orderby', 'type' );
$query->set( 'order', 'DESC' );
};
return $query;
}
Stick that in your functions.php file and you should be good to go.