How to intercept a 404 error

I'd like to intercept 404 errors and do some things before to show the 404 error page.

How can intercept the 404 error?

Answers 2

  • As was mentioned in a comment, template_redirect would be an appropriate hook for intercepting a 404 before the template is loaded.

    function wpd_do_stuff_on_404(){
        if( is_404() ){
            // do stuff
    add_action( 'template_redirect', 'wpd_do_stuff_on_404' );

    Refer to the Action Reference for the general order of actions on the front end. The main query runs between the posts_selection and wp actions, so that is the earliest you can determine that a request is a 404. The template is then loaded after template_redirect, so it's too late to set headers after that point.

  • Using below code you can directly redirect on home page when 404 call, please remove all code from the 404.php file and add below code.

    header("HTTP/1.1 301 Moved Permanently");
    header("Location: ".get_bloginfo('url'));

Related Questions