$conf, $runtime; function_exists('chdir') AND chdir(APP_PATH); $r = 'mysql' == $conf['cache']['type'] ? website_set('runtime', $runtime) : cache_set('runtime', $runtime); } function runtime_truncate() { global $conf; 'mysql' == $conf['cache']['type'] ? website_set('runtime', '') : cache_delete('runtime'); } register_shutdown_function('runtime_save'); ?>query - How to add variables to a template|Programmer puzzle solving
最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

query - How to add variables to a template

matteradmin10PV0评论

I am using a query argument detail to check if a custom template should be loaded. This works fine, but I also need to add some variables that can be accessed from within the template. Here I am using add_action('template_include' array($this, 'templateInclude'):

public function templateInclude($template)
{
    if (get_query_var('detail', false) !== false) {
        // Check theme directory first.
        $newTemplate = locate_template(array('detail.php'));
        if ($newTemplate != '')
            return $newTemplate;

        // Check plugin directory next.
        $newTemplate = plugin_dir_path(__FILE__) . 'templates/detail.php';
        if (file_exists($newTemplate)) {
            return $newTemplate;
        }
    }

    // Return default template.
    return $template;
}

The above works, but of course I am not able to actually set any variables for the template.

I tried using set_query_var() to set a variable that could be accessed using get_query_var(), but this does not really seem to be the best solution.

I also tried using add_action('template_redirect' array($this, 'templateRedirect'), which works but this neither seems to be a really good solution:

public function templateRedirect() {
    if (get_query_var('detail')) {
        $detailId = get_query_var('detail', null);
        // Set a variable 'data' that can be used inside the template
        $data = get_detail($detailId);
        include plugin_dir_path(__FILE__) . 'templates/detail.php';
        exit;
    }
}

Would be really great if someone has some nice way of adding custom variables for a specific template.

Articles related to this article

Post a comment

comment list (0)

  1. No comments so far