WordPress includes a 404 error page template in the theme, however the contents of this are not editable in the backend of WordPress (within the CMS).
Placing the code below in your themes 404.php
file enables you to create a WordPress page using the slug of 404-error
and the content of this page will be displayed when user lands on your sites 404 page.
Things to note
- The 404 page is often a page which is served a lot. Therefore you should keep it light and not have too many heavy queries taking place such as latest posts. Sticking to simply text and maybe an image is a good idea.
- As the 404 page is now a page in WordPress, you will probably want to set that page as
no-index
so that Google doesn’t index it and also you may want to remove it from the site map. WordPress SEO from Yoast certainly allows you to do the former.
<?php
/**
* 404 page template.
*/
// get the WordPress header template.
get_header();
// get the 404 page based on the page's slug
// you must have a WordPress page with the slug of "404-error".
$not_found_page = get_page_by_path( '404-error' );
// if we have a 404 page.
if ( null !== $not_found_page ) {
// get the blocks for the 404 page.
$blocks = parse_blocks( $not_found_page->post_content );
// create a var for the markup.
$content = '';
// loop through block.
foreach ( $blocks as $block ) {
// render this block into the content.
$content .= render_block( $block );
}
// output the 404 page content - the blocks!
echo $content;
} else {
?>
<p><?php esc_html_e( 'Sorry but the page you are looking for cannot be found.', 'perse-school-theme' ); ?></p>
<?php
}
// get the sites footer template.
get_footer();