Today I was tasked with creating a more dynamic 404 page in WordPress. My goal was to use keywords from the URL to run an advanced search & return the most relevant content.
Originally I was planning to use Smart 404 to customize the 404 and Relevanssi to search the site. Unfortunately out of the box these 2 plugins don’t work together. In this post, I’m going to show you how to create your own Smart 404 page using Relevanssi.
Smart 404 finds keywords in the URL and runs a search query using these keywords. Step 1 was getting the keywords. Looking at their code this is how they do it.
Copy and paste the code above into your 404.php theme file. If you were to echo $search_words you’d get your URL keywords. For example echoing $search_words on a 404 page with the slug of /wordpress-plugins/ would return ‘wordpress plugins’. The next step is using the search keywords with a Relevanssi search.
If you’re unfamiliar with Relevanssi it is a search plugin with advanced options like running a partial match search, adjusting content weights and more.
Relevanssi replaces the standard WordPress search with a better search engine, with lots of features and configurable options. You’ll get better results, better presentation of results – your users will thank you.
How to Query Relevanssi Search
Relevanssi has a function called relevanssi_do_query() to search queries outside of the search page. To use this function you need to define your search terms and how many posts to load per page. Once that is done you can just loop through the results.
Together this is what it looks like. Copy and paste this into your 404.php template.
Now when a user lands on a 404 page they’ll be given a list of the most relevant content from your site using a Relevanssi search.
Let me know if this was helpful, if you having any issues or have a better way of approaching this.