I would like to know the best part of the code to catch a 404 that doesn't match a template. However at this point I will check for the url string and output my own dynamic html if it matches a pattern. It is DYNAMIC content because there is no content in the wordpress backend for it. So I am looking to echo html and exit if it matches. If not then continue and 404 as normal.

In reference to this question too. Dynamic URL generates dynamic content



It's not possible to catch a non–match to template in WP because it will always match some template. The very last template it will fall back to will simply be index.php, the most generic one in template hierarchy.

In general the appropriate hook for such logic is typically template_redirect in template-loader.php. At this point the query is done, the conditional context is fully set up, but native template resolution and inclusion hadn't fired yet.

  • Ok then I mean catch a 404 for a non existent slug (therfore url) - so a 404 would be about to happen. Thanks for your advice I will checkout the template-loader file. – landed Jan 17 '17 at 22:19
  • So I now have everything working except that the server is returning a 404 page (as in effect wordpress sees it like that)..will try and force a normal header..somehow. – landed Jan 18 '17 at 17:27

You can make a 404.php file. That is a normal file to have as part of your theme. You can handle all of your logic in there and have it load your dynamic html in it.


You can use a function like the following in your functions.php file. I just tested and you can get most of what you need from the URL using the var_dump() placed in this function.

// borrowed from http://wordpress.stackexchange.com/a/1883/10907
function stoi2m1_404_override() {
    global $wp_query;

    // return if not a 404 page
    if (!$wp_query->is_404)

    // dump the data in the query, parameters from the URL
    echo '<pre>';
    echo '</pre>';

    /* resulted in something like this for me, Im using a custom post type movies
    array(4) {
        string(0) ""
        string(4) "missing"
        string(6) "movies"
        string(4) "missing"

    if ($wp_query->query['name'] == 'missing' ) { //what ever name/title of post you are looking for
        status_header( 200 ); // set the appropriate header
        $wp_query->is_404=false; // set is_404 to false

        // apply any more logic you need here
        // or include custom template file here
        // you will want to keep the usual template from loading   
add_filter('template_redirect', 'stoi2m1_404_override' );

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.