I have a WordPress website and a custom theme, and of course a 404.php
file. I have followed this amazing guide on making the 404 page template editable with the block editor.
My components on the 404 page appear correctly when I go to /404
(or for that matter, any invalid link), however, when going to /404
, the user is redirected to /404-2
This is the behavior I would like to fix. When the user goes to /abc
(an invalid page) then the 404 is shown and they ae not redirected and still on /abc
(which is as intended).
I checked the page in WP and the URL slug is set to /404-2
and attempting to change it to 404 just defaults back to 404. It seems that this is due to 404 being a number and default WP behavior. But this just tells me why the problem occurs; I do not know how to override or correct this behavior. Thanks in advance.
2
Answers
Fixed it by hooking onto
do_redirect_guess_404_permalink
See https://developer.wordpress.org/reference/hooks/do_redirect_guess_404_permalink/
As you’ve found, the page title "404" (or any numeric title) will always be rewritten to "404-2", this ensures the title is distinct/never confused with a numeric post/page id.
A simple solution would be to rename the page to "404 page" and update the php function to
get_page_by_title( '404 page' )
. This would give your page more SEO friendly url of/404-page
and not require trying to change permalinks/rewriting of the .htaccess file.An alternative to consider is migrating your custom theme to a block theme if using WordPress 5.9 or higher. This would enable you to create a true "404" page template using the Block Editor that can be edited via the
Site Editor > Templates
. The Site Editor enables you to add new templates, save and export them for easily creating your own templates for your custom theme. Starting with a base theme like Twenty Twenty Two is a good way to see what is possible. It’s very different to creating a "classic" php-based theme; though the advantage of block templates and the Site Editor is a great benefit for future-proofing your theme.