1

I don't want to change the core SEARCH function. I have default search function and only updating search.php file in the theme. I added search_filter function into functions.php.

function search_filter($query)
{
    if (!is_admin() && $query->is_main_query()) {
        if ($query->is_search) {
            $query->set('post_type', array('page', 'post', 'fsgallery'));
            $query->set('order', array('post_date' => 'DESC'));
        }
    }
}
add_action('pre_get_posts', 'search_filter');

I have 3 post_type in my Wordpress and I want to show all page result first and then combine POST and GALLERY results with ordered by date. Right now order by DESC result shows everything by ordered and could not show page first.

What I need is: I want to show all page result first. After that I want to show post and gallery ordered by date.

  • Look here – nmr Aug 9 '19 at 10:52
  • I already tried this one. First its not combining post and fsgallery post_types. I need to combine them and order by Desc. Also it breaks core search. I mean when i search some words the result shows many wrong pages. – Bayanaa Aug 9 '19 at 20:10
  • ooh wow. WP search is finding from image alt tag and it shows many pages. It was my fault. But its still not combining post and gallery :P.Otherwise all close to fix – Bayanaa Aug 9 '19 at 20:32
0

Here is the code from the provided link after adaptation.

add_filter( 'posts_orderby', 'se344727_custom_search_order', 10, 2 );
function se344727_custom_search_order( $orderby, $query )
{
    global $wpdb;

    if (!is_admin() && $query->is_main_query())
    {
        if ($query->is_search) 
        {
            // -- sort by: type, title, date --
            // " ELSE 2 END ASC, " . $orderby;

            // -- sort by: type, date --
            // " ELSE 2 END ASC, {$wpdb->prefix}posts.post_date DESC;

            $orderby =
                " CASE WHEN {$wpdb->prefix}posts.post_type = 'page' THEN 1 " . 
                " ELSE 2 END ASC, " .
                $orderby;
        }
    }    
    return $orderby;
}
  • Yes your right. It's working perfect. I wanted to up vote. but it shows "Votes cast by those with less than 15 reputation are recorded, but do not change the publicly displayed post score." – Bayanaa Aug 13 '19 at 23:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.