Template redirect template loaded, but the header 404

I’ve created a template redirect for a given url, ex.: test.com/test

Test is page is not exists, i’m just checking the url from query_vars, if its match, i load the template with

Read More
include(file.php);
exit;

The page loads and show what i expect, but the title is Page not found. I solve this with a filter, but i saw that the whole page comes with a 404 status. Btw i saw that the builtin multisite activation message also has a 404 header. (I’m working on localhost.)

How can i solve this without creating the page itself in wp?

Related posts

1 comment

  1. You are essentially trying to create a “fake” page without having to create a physical page in the WordPress database and for that, you will need custom re-write rules.

    For more details see my answer here: Setting a custom sub-path for blog without using pages?

    Quick overview:

    step 1: setup your custom rewrite rules

    add_action('init', 'fake_page_rewrite');
    
    function fake_page_rewrite(){
    
        global $wp_rewrite;
        //set up our query variable %test% which equates to index.php?test= 
        add_rewrite_tag( '%test%', '([^&]+)'); 
        //add rewrite rule that matches /test
        add_rewrite_rule('^test/?','index.php?test=test','top');
        //add endpoint, in this case 'test' to satisfy our rewrite rule /test
        add_rewrite_endpoint( 'test', EP_PERMALINK | EP_PAGES );
        //flush rules to get this to work properly (do this once, then comment out)
        $wp_rewrite->flush_rules();
    
    }
    

    Step 2: properly include a template file on matching your query variable,

    add_action('template_redirect', 'fake_page_redirect');
    
    function fake_page_redirect(){
    
        global $wp;
    
        //retrieve the query vars and store as variable $template 
        $template = $wp->query_vars;
    
        //pass the $template variable into the conditional statement and
        //check if the key 'test' is one of the query_vars held in the $template array
        //and that 'test' is equal to the value of the key which is set
        if ( array_key_exists( 'test', $template ) && 'test' == $template['test'] ) {
    
            //if the key 'test' exists and 'test' matches the value of that key
            //then return the template specified below to handle presentation
            include( get_template_directory().'/your-template-name-here.php' );
            exit;
        }
    }
    

Comments are closed.