How-To Guides and Blog

Display Random Posts on ⚠️ 404 Page

NBH Support
No Comments

If you want to display a random posts on WordPress 404 page, then you can simply add this code to your 404 template where you want to display a random list of posts from your site.

$posts = get_posts('orderby=rand&numberposts=5'); 
   foreach($posts as $post) { ?>
        <li><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a>
   <?php } ?>

This same query can be modified to show the most popular posts, most commented posts among others.

If you want to further improve your website and detect 404 errors as soon as they occor, check this article that describes the process of improving the 404-page on your WordPress website to make it more useful in general.

You can also use a WordPress plugin such as WP 404 Auto Redirect to automatically redirect 404 pages to similar posts based on Title, Post Types & Taxonomies. If nothing similar is found, visitors will be redirected to the homepage or a custom URL.