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.

// Extract any GET parameters from URL
$get_params = "";
if ( preg_match("@/?(\?.*)@", $_SERVER["REQUEST_URI"], $matches) ) {
    $get_params = $matches[1];
}

// Extract search term from URL
$patterns_array = array();
$patterns_array = explode( '\n', $patterns );

$patterns_array[] = "/(trackback|feed|(comment-)?page-?[0-9]*)/?$";
$patterns_array[] = "\.(html|php)$";
$patterns_array[] = "/?\?.*";
$patterns_array = array_map(create_function('$a', '$sep = (strpos($a, "@") === false ? "@" : "%"); return $sep.trim($a).$sep."i";'), $patterns_array);

$search = preg_replace( $patterns_array, "", urldecode( $_SERVER["REQUEST_URI"] ) );
$search = basename(trim($search));
$search = str_replace("_", "-", $search);
$search = trim(preg_replace( $patterns_array, "", $search));


$search_words = trim(preg_replace( "@[_-]@", " ", $search));

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.

Relevanssi – WordPress.org

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.

if (!empty($search_words)) {	
	$query = new WP_Query();
	$query->query_vars['s'] = $search_words;
	$query->query_vars['posts_per_page'] = 10;
	relevanssi_do_query($query);
} 


foreach ($query->posts as $r_post) {
	$link = get_permalink($r_post->ID);
	$title = get_the_title($r_post->ID);
	
	echo '<li><a href="' . $link . '">' . $title . '</a></li>';
}

Together this is what it looks like. Copy and paste this into your 404.php template.

// Extract any GET parameters from URL
$get_params = "";
if ( preg_match("@/?(\?.*)@", $_SERVER["REQUEST_URI"], $matches) ) {
    $get_params = $matches[1];
}

// Extract search term from URL
$patterns_array = array();
$patterns_array = explode( '\n', $patterns );

$patterns_array[] = "/(trackback|feed|(comment-)?page-?[0-9]*)/?$";
$patterns_array[] = "\.(html|php)$";
$patterns_array[] = "/?\?.*";
$patterns_array = array_map(create_function('$a', '$sep = (strpos($a, "@") === false ? "@" : "%"); return $sep.trim($a).$sep."i";'), $patterns_array);

$search = preg_replace( $patterns_array, "", urldecode( $_SERVER["REQUEST_URI"] ) );
$search = basename(trim($search));
$search = str_replace("_", "-", $search);
$search = trim(preg_replace( $patterns_array, "", $search));


$search_words = trim(preg_replace( "@[_-]@", " ", $search));

if (!empty($search_words)) {	
	$query = new WP_Query();
	$query->query_vars['s'] = $search_words;
	$query->query_vars['posts_per_page'] = 10;
	relevanssi_do_query($query);
} 


foreach ($query->posts as $r_post) {
	$link = get_permalink($r_post->ID);
	$title = get_the_title($r_post->ID);
	
	echo '<li><a href="' . $link . '">' . $title . '</a></li>';
}

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.