On Drupal site A we have a bunch of links to non-Drupal site B. For marketing and tracking purposes all these links have a different URL variable appended to them, so that when a user registers on site B we can determine where on site A they came from.
At the moment I use page.tpl.php to create the variable ($forceCode
) but it now transpires I need this variable to be available to node.tpl.php too, and I feel like there must be a less hacky and more universal way of doing this, probably using a preprocess function in template.php that right now seems beyond my comprehension level.
PLAIN LANGUAGE EXPLANATION
$specialPages
is an array of node IDs that need a special code.
$specialFolders
is an array of taxonomy IDs that need a special code.
- If the current node ID matches any in the
nid
array, I set the variable accordingly. - If not then I get the category (taxonomy) of the current node, or if the current page is a taxonomy term itself then use its own
tid
.- Then using this taxonomy ID I get all other
tid
s that are parents of thattid
. - Then I look for matches of any of these taxonomy IDs in my array of special
tid
s in order to set the variable.
- Then using this taxonomy ID I get all other
- If the current page has not matched any of my special nodes or taxonomies, the variable remains its default value.
ACTUAL CODE
// we later restrict our parent taxonomy search to certain types but it's not strictly necessary
$contentTypes = array("article","advpoll","event");
$specialFolders = array(
276 => "events",
292 => "free-dating",
498 => "date-explorer"
);
$specialPages = array(
22 => "reviews",
86 => "texting"
);
$forceCode = "default";
// check for specific page first
if (@array_key_exists($node->nid,$specialPages)){
$forceCode = $specialPages[$node->nid];
} else {
// there was no entry for this nid, let's check parent terms
$parentTerms = array();
$hasParents = false;
if (arg(0) == "taxonomy") $hasParents = arg(2);
if (@in_array($node->type,$contentTypes)) {
$category = field_view_field('node', node_load($node->nid), 'field_category');
$hasParents = $category['#items'][0]['tid'];
}
if ($hasParents !== false) {
$parents = taxonomy_get_parents_all($hasParents);
foreach ($parents as $term){
$parentTerms[] = $term->tid;
}
}
foreach ($parentTerms as $tid){
if (array_key_exists($tid,$specialFolders)){
$forceCode = $specialFolders[$tid];
continue;
}
}
}
hook_preprocess()
perhaps?function hook_preprocess(&$variables, $hook){ $variables['myNewVar'] = "anything"; }
has not lead to me being able to access $myNewVar from either page.tpl.php or node.tpl.php on any type of page. Also tried by prefixing function with themename.