Skip to content

Commit

Permalink
If we 404, run a search based on the URI
Browse files Browse the repository at this point in the history
Maybe we'll find what they were looking for and avoid forcing them to
do a search, or worse, just leave.
  • Loading branch information
joshbetz committed Sep 14, 2012
1 parent f35d4ba commit 493afdf
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
1 change: 1 addition & 0 deletions 404.php
Expand Up @@ -9,6 +9,7 @@
<div class="article">
<p><?php _e( "It seems you've reached a page that doesn't exist. Try using the search form below.", 'v11' ); ?></p>
<?php get_search_form(); ?>
<?php v11_possibly_related_posts(); ?>
</div>
</article>

Expand Down
32 changes: 32 additions & 0 deletions functions.php
Expand Up @@ -346,4 +346,36 @@ function v11_url_grabber( $content ) {

return esc_url_raw( $matches[1] );
}
endif;

if ( ! function_exists( 'v11_possibly_related_posts' ) ) :
/**
* On 404 pages, run a search based on the URI.
* Maybe we'll come up with what they were looking for
* and avoid forcing them to do a search
*/
function v11_possibly_related_posts() {
if ( ! is_404() )
return;

$uri = esc_url( $_SERVER['REQUEST_URI'] );
$uri = array_pop( explode( '/', $uri ) );

$search = trim( preg_replace( '@[_-]@', ' ', $uri ) );
$posts = get_posts( array( 's' => $search ) );

if ( count( $posts ) == 0 )
return;

$related = "<h2>Maybe these will help?</h2>";
$related .= "<ul>";
foreach ( $posts as $post ) {
$title = $post->post_title;
$permalink = get_permalink( $post->ID );
$related .= "<li><a href='$permalink'>$title</a></li>";
}
$related .= "</ul>";

echo $related;
}
endif;

0 comments on commit 493afdf

Please sign in to comment.