How to prioritize pages over posts when searching?

So I’m new to WordPress and as such I’m not entirely sure how things work with it. But one of the problems I am having is that the default search feature treats Pages and Posts the same.

For example, I have Page called Java, then I have several posts titled Learning Java #… If I search Java, the Page comes up as the last item and the posts come before it. I’m wondering if there is a way to tweak the search so I have Pages listed first.

Read More

Also, I’ve googled this a bit and have seen some supposed PHP fixes to this problem, but as I said, I’m new to WordPress so I’m not sure where exactly I’ll be editing in PHP. Any help would be appreciated, and if you comment, please treat me as a real beginner and break things down so I can understand it better.

Related posts

Leave a Reply

1 comment

  1. You need to put this code in your function.php:

    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');
    

    By default search function work with all post type, and you can specify in which you want to make a search:

    $query->set('post_type', array('page','post'));
    

    hook pre_get_posts will fired before get any posts, so we need to modify it. And set some arguments, to get posts with specific criteria.