• Hey Guys,

    I have been working on a plugin that uses the template_redirect action to render a custom page on the WordPress front-end.

    The template_redirect action works as expected as it renders the page on the front-end correctly, but the problem is the template_redirect action is being called twice and its calling my function twice, which is making this unnecessary 2nd call, affecting performance.

    I have traced the code with xdebug and noticed that this second call to the template_redirect hook happens when I echo the body output HTML.

    I look forward to any suggestions how I can prevent this second call to the template_redirect hook (or why this happens), or if there is any other approach to display this front-end page without having my my_page_render() function called more than once.

    These are the relevant parts of the code I have:

    File: /plugins/my_plugin/main.php

    <?php
    /*
    Plugin Name: My Plugin Name
    */
    include WP_PATH.'/plugins/my_plugin/classes/plugin_setup_class.php';
    new plugin_setup_class();

    File: /plugins/my_plugin/classes/plugin_setup_class.php

    <?php
    class plugin_setup_class {
      public $loader;
      public function __construct()
      {
        if(!is_admin())
        {
          $this->loader = new public_loader();
          $this->init();
         }
      }
      public function init()
      {
        add_action('template_redirect', array($this->loader, 'my_page_render'));
      }
    }

    File: /plugins/my_plugin/classes/public_loader.php

    <?php
    class public_loader.php {
      public function my_page_render()
      {
        global $wp_query, $wp;
        if($wp_query->query_vars['post_type'] == 'my_post_type' ||
    	preg_match("#".URL_PREFIX."[/]([A-Za-z0-9]+)/?#", $wp->request, $matches))
        {
           /* Code that gets data here */
           /* Then */
           include MY_PLUGIN_PATH . '/header.php';
           echo $html_body;  // When this echo line runs, the hook template_redirect
           // fires again and executes this whole function again.
           // Need to run this function only once, not twice.
           include MY_PLUGIN_PATH.'/footer.php';
           exit;
        }
      }
    }

The topic ‘template_redirect Hook: strange behavior’ is closed to new replies.