Filter to change the content of 404 page

I have created custom rewrite rules. These rules now go to 404 page as expected. I can use action hook template_redirect to change the template matching query_var.

But I don’t want to create separate template files as the page structure depend on the current theme in use. Rather I just want to change the content and title. I have tried change the content using the_content filter, but it seems the filter doesn’t even get called for 404 page.

I also tried loading index.php template and then using the_content filter, but it also doesn’t work.

Is there any way to achieve this?

2 Answers
2

I have a 404 plugin that does basically what you’re needing (if I understand correctly), only it creates a new page (using the same templates from your theme) and registers it as the 404 page. If you already have an existing WordPress page (NOT php file) then you could use code similar to the following to turn it into your new 404 page. Note: You do need to customize this a bit. See the notes in the code below.

//redirect on 404
function redirect_404() {
    global $options, $wp_query;
    if ($wp_query->is_404) {
        $page_title = $this->options['404_page_title'];//replace with your page title
        $redirect_404_url = esc_url(get_permalink(get_page_by_title($page_title))); 
        wp_redirect( $redirect_404_url );
        exit();
    }
}

//Make sure proper 404 status code is returned
function is_page_function() {
    global $options;
    $page_title = $this->options['404_page_title'];//replace with your page title
    if (is_page($page_title)) {
        header("Status: 404 Not Found");
    }
    else {
        return;
    }
}

//Register Hooks
add_action( 'template_redirect', 'redirect_404');
add_action('template_redirect', 'is_page_function');

If you want to checkout the full plugin code you can do so here: http://wordpress.org/plugins/404-silent-salesman/

Hope that helps!

Leave a Comment