7

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

How can intercept the 404 error?

  • Are you getting a WordPress error page or a server one? – s_ha_dum Jul 13 '15 at 15:23
  • Think I'm linking to a post that doesn't exist: I want to intercept that kind of 404. Then, if possible, I'd like to know the passed id or the passed slug and use it to do other things. – Aerendir Jul 13 '15 at 15:25
  • 1
    Currently I haven't the error: I'm developing a plugin that has to intercept 404 errors generated by wordpress itself when the url is of a post that doesn't exist. I don't have a real 404 error. I publish a post (call it A) and this post links to the post "B". Post "B" doesn't exist (or is scheduled or only a draft or its link is wrong). I want to intercept the 404 error generated when I go from Post A to Post B. I produce the error linking from Post A to an inexistent post, example.com/?p=1234567890 or example.com/non-existent-post – Aerendir Jul 13 '15 at 15:41
  • 1
    The template_include or template_redirect hooks might be useful too. Really, your question/problem is pretty vague at this point. – s_ha_dum Jul 13 '15 at 15:45
  • 1
    Maybe it's a vague question, but the point is that i want to intercept the 404 error in a plugin I'm writing: i think is sufficiently complete as request, or not? This is my first plugin, so maybe I'm missing some information... Anyway, I've read that page, but as said, I want to intercept the 404 error in a plugin, don't want to edit a 404 template. I want my functionality be available independently of the theme in use... – Aerendir Jul 13 '15 at 19:14
15

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.

-1

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.

<?php
header("HTTP/1.1 301 Moved Permanently");
header("Location: ".get_bloginfo('url'));
exit();
?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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