Support » Plugins » Hacks » template_include versus template_redirect used by plugin

  • Howdy.

    I will try to keep this brief. I am wanting to add a custom slug to the WP_Rewrite so that all URLs under a specific URI are re-routed to my plugin and bypasses the default theme altogether.

    An example:

    Normal Functionality -|

    Add This -|

    I am using MVC or my plugin, so I want to send anything under /my-slug/ to my own router that will then call the correct controller and so on. None of these controllers use the WP Themes. They have a totally separate design. This can all happen before the wp_query, but it doesn’t have to.

    I have noticed two ways to do this using hooks: template_include and template_redirect

    My question is: which of these is cleaner? Is there one that would be a better choice for performance? I would like to avoid using exit() at the end of my intercept so that (after my page has been executed) WordPress can continue with its shutdown functions.

    Thank you,

Viewing 5 replies - 1 through 5 (of 5 total)
  • Moderator bcworkz


    The two hooks occur fairly close to each other, both after WP_Query. The ‘template_redirect’ fires before the code determines which template to load, ‘template_includes’ after. If your callback needs to know what template was picked or needs to influence that pick, you need ‘template_includes’. You cannot influence the template picked from ‘template_redirect’, but it is more efficient if you are going to bypass the template pick anyway.

    If you hook ‘template_redirect’, execute your code, then return, the rest of the normal process will continue. If you return from ‘template_redirect’, there is no efficiency gain over using ‘template_includes’, either one will work just as well.

    Thank you. Is there a better way to do this before WP_Query has taken place? I am wanting to load a plugin PHP’s file and have no need for the Post query process.

    Moderator bcworkz


    For rewrite rules use the ‘init’ action. Anything after that is actually too late. I should have mentioned that, I paid little attention to what you were doing and just answered your question. My bad.

    To be clear, a plugin’s PHP file is loaded immediately after core files are loaded (assuming the plugin is activated) without any specific code from you. Any code in that file not in function definitions, such as add_action() are executed immediately. This would be too early for rewrites, hence the ‘init’ hook which is fired immediately after WP is pretty much fully loaded.

    Thank you. That should work wonderfully 🙂

    I’ve been playing with this and I think Rewrites are actually the better option for me. I am going to re-post this question under that topic. Thank you for your help!

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘template_include versus template_redirect used by plugin’ is closed to new replies.