Returning search results by relevance, including Custom Post Types

Yes, Relevanssi will do the trick for you, but you need some additional code. Relevanssi has a filter hook relevanssi_hits_filter, which lets you modify the list of results.

So, you need to create a function that will take the hits and if there’s a species profile that matches the search query, the function will add it to the top of the results.

Something like this:

add_filter('relevanssi_hits_filter', 'fish_filter');
function fish_filter($hits) {
    // $hits[0] has the array of hits found
    // $hits[1] has the search query
    $results = array();

    if ($hits[1] matches a species) {
        $sp_post = get_post(the correct post ID);
        $results[] = $sp_post;
    }
    if (posts about species exist) {
        $sp_posts = fetch them somehow;
        array_merge($results, $sp_posts);
    }

    // and so on for other article types

    // then the rest of the posts
    foreach ($hits[0] as $hit) {
        if (!in_array($hit, $results)) $results[] = $hit;
        // this skips all the posts that are already in the results
    }

    $hits[0] = $results;
    return $hits;
}

That’s the basic structure. Of course there are lots of details you need to fill in yourself, how to recognise the posts you want and how to fetch them, but I don’t think there’s an easier solution than this.

Leave a Comment