Tip
Hi. This is something I needed the other day, and I thought I would share it.
How to add template tags at runtime.
The basic problem was I needed an easily accessible index of cat ids.
This is for filtering a {exp:weblog} call.
So, I want to be able to do:
{exp:weblog:entries category="{cat_id_{segment_1}}"}But I don’t want to have to put the cat_id_whatever as global variables through the cpanel.
I wanted these template tags to be generated from the cat info in the DB. This allows for easy adding of new sections (providing they follow the naming rules).
My basic template design is to have one site/index.php which then pulls together the various pieces (site/.header, site/.footer…).
So, at the top of my site/index.php I add:
global $DB, $TMPL;
//What we're doing here is adding it to the TMPL global vars, so we can access this info like
//{cat_id_catShortNameHere}
//or if we need it at a PHP stage,
//$TMPL->global_vars['cat_id_catShortNameHere']
$cats_q = $DB->query("SELECT cat_id, cat_url_title FROM exp_categories");
foreach ($cats_q->result as $row) {
$TMPL->global_vars['cat_id_'.$row['cat_url_title']] = $row['cat_id'];
}One thing to note, this has to be in a template that loads before you try to call the tag. You can see the order templates are processed in by turning on template debugging output.