Sort WooCommerce products first in search results

When shoppers search a WordPress website, you want them to find products first before listing any articles and pages. And it’s surprisingly easy to achieve, with a simple filter hook.

Before I continue, I must first say that anyone wanting to fine-tune their WordPress searches should check out the very fine plugin, SearchWP. It revolutionises searching in WordPress.

With that out of the way, if all you want to do is bring products to the top of your search results, here’s a simple solution. Tell WordPress that it should order posts of type “product” first, and anything else second. There’s an easy way to do that, and here’s the SQL for the order by clause:

IF(wp_posts.post_type = 'product', 0, 1)

That function call returns 0 for posts with post_type “product”, and 1 for anything else. Simple.

Add this code snippet to a simple plugin, or your theme’s functions.php file, and it will insert that order by clause whenever you’re doing a search across all post types:

/**
* filter searches to put products ahead of other post types
* @param string $order_by
* @param WP_Query $query
* @return string
*/
add_filter('posts_orderby_request', function($order_by, $query) {
    global $wpdb;

    // make sure it's a search query with no post type specified
    if (!empty($query->query_vars['s']) && empty($query->query['post_type'])) {
        // compose order by clause to hoist products above other post types
        $products_first = "IF({$wpdb->posts}.post_type = 'product', 0, 1)";

        // insert clause at front of existing order by clause
        $order_by = empty($order_by) ? $products_first : "$products_first, $order_by";
    }

    return $order_by;
}, 10, 2);

Job is done, with the money posts first.

Facebooktwittergoogle_plusredditlinkedinmailFacebooktwittergoogle_plusredditlinkedinmail