add_rewrite_rule works in themes function php but when moved into plugin it stops working

As stated in the title this code is working in my functions php file in the active child theme. I do not have much if anything installed as this is being developed in a vanilla WP installation.

here is the code I am using…

add_action('init', 'foo_add_rewrite_rule');
function foo_add_rewrite_rule(){
    add_rewrite_rule('^foobar?','index.php?is_foobar_page=1&post_type=custom_post_type','top');
    //Customize this query string - keep is_foobar_page=1 intact
}

add_action('query_vars','foo_set_query_var');
function foo_set_query_var($vars) {
    array_push($vars, 'is_foobar_page');
    return $vars;
}

add_filter('template_include', 'foo_include_template', 1000, 1);
function foo_include_template($template){
    if(get_query_var('is_foobar_page')){
        $new_template = WP_CONTENT_DIR.'/themes/your-theme/template-name.php';
        if(file_exists($new_template))
            $template = $new_template;
    }
    return $template;
}

this works perfect when in the the active child theme but when I move it out and into the plugin it fails.

i am using flush_rewrite_rules(); in the plugin and have disabled/enabled it to flush the rewrite rules.

I have set the constants to pull from the plugin directory in the templae function.

Can someone please tell me what I am missing?

Read more here: add_rewrite_rule works in themes function php but when moved into plugin it stops working

Leave a Reply

Your email address will not be published. Required fields are marked *