2

I'm developing a plugin that create some pages and set a specific template for each of these pages. It creates a page in which it sets a template for 404 - not found, how can set this specifc page as WordPress 404 (so it will be displayed when needed)?

3
  • 1
    WP doesn't use pages as 404's it uses the 404.php template in the theme. You would need to detect a 404 and manually load and display your page somehow, overriding the template loaded. Note that 404's should be the fastest lightest weight page your site can deliver since it'll be loaded if anything is broken, e.g. bad links, or images. You don't want a page with 10 broken resources to load 10 pages worth of server resources, or for spambots to trigger expensive queries by accident
    – Tom J Nowell
    Oct 15, 2021 at 14:38
  • How can I detect a 404 error and, most importantly, how can I override the theme's 404.php template with my custom template?
    – icolumbro
    Oct 15, 2021 at 14:44
  • Why not just modify the theme's 404.php to be as you like (using a CHILD theme, of course, so it doesn't get overwritten on theme updates)? That is the easiest method that requires no other code or mods.
    – Trisha
    Oct 19, 2021 at 20:43

1 Answer 1

5

You can filter 404_template and return the path of your custom file from the plugin directory like this:

add_filter( 
    '404_template', 
    fn() => plugin_dir_path( __FILE__ ) . '404.php' 
);

This hook exists only when a 404 happens, so you don't need any custom detection.

1
  • Thank you, it works like a charm!
    – icolumbro
    Oct 15, 2021 at 15:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.