How Can I Query WordPress Posts and Sort by Their Relevance?

September 29, 2017

WP_Query allows us to query our WordPress posts and return results based on the taxonomy terms those posts are tagged with. It does this quite well, and can then sort the posts by date, alphabetically, menu order, etc. However, it isn’t able to sort the results based on how relevant the post is – meaning how well it actually matches the selected terms.

After quite a bit of Googling, I wasn’t able to find the perfect solution for my needs, but I did find two solutions I could merge together.

First off, I started with this plugin by Mannie Schumpert:

https://github.com/mannieschumpert/wp-relevance-query.  This seemed like the perfect answer, but it is a little outdated and it needed some tweaking to fit my needs.

The other resource I used was this:

https://wordpress.stackexchange.com/questions/74381/wp-query-sort-results-by-relevance-most-tags-taxonomy-terms-in-common which prompted me to use usort.

Updated plugin:

I was able to update Mannie Schumpert’s plugin to work for my needs which can be found here. After the plugin is installed all you need to do to run a WP Relevance Query is:

$my_query = new WP_Relevance_Query( $args );

NOTE: The query can only be done using the term ID and not the slug.

Another nice snippet is actually printing out the post’s relevance with following:
<?php
$getPostObject = get_post();
echo round($getPostObject->relevance) . '% match';
?>

Disclaimer: the edited plugin hasn’t been fully tested for all possible scenarios. However it did work for mine, which was querying a custom post type using multiple taxonomies using the ‘OR’ relation.

Stay in Touch!

Subscribe to our newsletter.

Solutions Architecture

browse through our blog articles

Blog Archive