• I tried to add a function for WP default search, I will like to make it result to shoe page items first, then post items, but it’s not quite working yet.
    I’m not using any plugin for search.
    Here’s my code:

    First one

    <?php 
    	function filter_search($query) {
        if ($query->is_search) {
        $query->set('post_type', array('page', 'post'));
        
        };
        return $query;
    };
    add_filter('pre_get_posts', 'filter_search');
    ?>

    Second one I tried:

    <?php
    	function filter_search($query) {
        if ($query->is_search) {
        $query->set('post_type', 
        	   array(
        	   'post_type'=>'page', 
        	   'orderby' => 'title',
    		   'order'   => 'DESC',
    		   )
               );
    } else {
        $query->set('post_type', 
        	   array(
        	   'post_type'=>'post', 
    		   'order'   => 'DESC',
    		   )
        	   );
    };
    
    return $query;
    add_filter('pre_get_posts', 'filter_search');
    ?>

    Thanks for the help!

Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator bcworkz

    (@bcworkz)

    Your first code is good for ensuring searches include both pages and posts, but does not affect ordering at all. Your second code is on the wrong track, give up on that line of reasoning ??

    In your first example, add another call to $query->set() that sets the “orderby” query var to “post_type”. By default, posts will come before pages. To reverse this, add another $query->set() call to set “order” query var to “ASC”.

    Thread Starter madebymt

    (@madebymt)

    @bcworkz

    Thank you so much for responding to my question, I tried adding a custom query for it. like
    $args=(array(
    ‘post-type’=>’page’,
    ‘order-by’=>’title’
    ))
    in the search page, but it’s not working.

    Moderator bcworkz

    (@bcworkz)

    IMO, you are better off altering the main default query through “pre_get_posts” than you are creating a custom query. For one thing, custom query pagination can be tricky to implement. Another is you are basically throwing out a completed query and making another one, not very efficient.

    What I had suggested previously is this:

    function filter_search( $query ) {
        if ($query->is_search) {
          $query->set('post_type', array('page', 'post'));
          $query->set('orderby', 'post_type');
          $query->set('order', 'ASC');
        };
        return;
    };
    add_action('pre_get_posts', 'filter_search');

    Note that pre_get_posts is an action, not a filter. The query object is passed by reference, so called methods are acting directly upon the original object. Nothing needs to be passed back.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘search result page first then post’ is closed to new replies.