Show custom data instead of 404

I’m currently developing a plugin to display some custom data on my wordpress site.

For example I have a data named abc. If a visitor try to access localhost/wordpress/abc, it should display the data programatically from code. But if a valid post url is accessed like localhost/wordpress/existing-post it should still display the post.

Read More

I’ve currently looking into trapping 404 redirect using template_redirect action and redirect_canonical filter, but the solution doesn’t feel right. Also I’m looking into using custom post type but not sure whether it’s suitable.

I’ve tried by create a post for each data, and use the_content filter to display the detail of the data, but this method generate too many posts so I’m looking for a cleaner alternative.

The data I have is generated in the background over time. So it will grow to thousands or tens of thousands in the future.

Thank you.

EDIT:

I’ve adopted 404 Tools plugin by toscho. These is the essential part that I’ve modified and use

add_filter( '404_template', 'myplugin_display_data' );
public function myplugin_display_data( $template )
{
    status_header(200);
    new self;
    //For now forward everything to my own page for testing purpose
    return dirname(__FILE__) . '/myplugin-page.php';
}

Now I notice that the output will have error404 in part of the CSS class of the body, which still render the output like 404. How should I make it like a post or page without manually overriding variables $wp_query, e.g. doing $wp_query->is_page = true;

I’m looking for an elegant way to do this.

EDIT:
I’ve added

    global $wp_query;
    $wp_query->parse_query("/");

After status_header, and now the page is displayed the way I wanted. Thanks.

Related posts

Leave a Reply

1 comment

  1. You may take a look at my 404 Tools plugin. I run a filter on '404_template' there. The filter function is getting the template URL as an argument, and it is still possible to send HTTP headers.

    You could hook into this filter too, prepare some data you may need to print out later, change the template (eg.: to single.php) and add a do_action( 'print_my_custom_data' ); to your single.php.