0

My client's website has a blog category and many product categories. She would like the search results to include the blog posts, but have the product posts first.

I can see two major implementation options

  1. Change the search query in functions.php
  2. Re-sort the search query results in the search.php template file

My question is: has anyone implemented this task, what implementation method did you use, and what issues did you have in the process?

I have searched for an answer to this specific situation and come up empty.

1 Answer 1

1

If I were you, I would likely use the posts_search_orderby hook to change the search ORDER BY clause, because that way, the sorting would work with pagination.

So for example in your case, you would want to sort by the post type like so: (well, if the "product posts" is of a different post type?)

// In functions.php:

add_filter( 'posts_search_orderby', 'my_posts_search_orderby', 10, 2 );
function my_posts_search_orderby( $orderby, $query ) {
    if ( $query->is_main_query() && is_search() ) {
        global $wpdb;
        $orderby = "{$wpdb->posts}.post_type";
    }

    return $orderby;
}

But if you just want an on-same-page sorting, then you can just go with the second option, like so which uses the native usort() and strcmp() functions in PHP:

// In functions.php:

add_filter( 'the_posts', 'my_the_posts', 10, 2 );
function my_the_posts( $posts, $query ) {
    if ( $query->is_main_query() && is_search() ) {
        usort( $posts, function ( $a, $b ) {
            return strcmp( $a->post_type, $b->post_type ); // A-Z (ASCending)
//          return strcmp( $b->post_type, $a->post_type ); // Z-A (DESCending)
        } );
    }

    return $posts;
}

That, however, uses the the_posts hook instead of modifying the search results template, but the point is, do the sorting manually after the posts have been retrieved. :)

And if you actually meant to sort by the post categories, then this may not be a solution for you, but the same concept (or hooks) can be used.

3
  • Your reply is very helpful! I will use your suggestions and reply with my results. Jan 2, 2021 at 17:40
  • I should have guessed that there is an "orderby" function in WordPress. Running with that, I changed the order to DESC. And, it's working. The site is a lumber yard. Now the wood types are at the top and the how to's are afterwards, when an internal search is done on a wood species. Jan 2, 2021 at 21:47
  • Glad to hear that, and happy new year! :)
    – Sally CJ
    Jan 3, 2021 at 0:42

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.