1

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?

1

When a plugin is activated, the activation hook is the only code that runs on that request. If you flush rewrite rules on activation, your rule isn't in the array of rules that everything gets rebuilt from, unless you explicitly add it first in the activation hook.

register_activation_hook( __FILE__, 'myplugin_flush_rewrites' );
function myplugin_flush_rewrites() {
    // call your function that adds the rule here
    // (it should also be hooked into 'init')
    foo_add_rewrite_rule();
    flush_rewrite_rules();
}

Your rule still has to be added on init on every request, because some other code, or a permalink settings page load, can flush rules on any request.

  • I have been looking for this and I cannot figure out how to set the title meta for the custom route. Any idea how I can get set the page title meta for the tabs etc. – phlipinmi May 18 '17 at 20:07
  • Do you mean the <title> tag? The filter is post_type_archive_title if the query is identified as a post type archive. – Milo May 18 '17 at 21:51

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.