showing a block based on url or taxonomy term

2007-06-18 / jpoesen

For reasons I won’t get into, I needed to be able to show a block if a certain keyword was present on a fixed position in the url, or if the current node had that same keyword as taxonomy term.

The code below shows the code that needed to be added to the section “show only if this code returns true” of the block in question.


$dept = “IT”;
$dept_in_url = arg(0);
$current_nid = 0; //default

if (arg(0) == ‘node’ && is_numeric(arg(1))) { $current_nid = arg(1);
}

$my_terms = taxonomy_node_get_terms($current_nid);
sort($my_terms);
$dept_in_taxterm = $my_terms0->name;

return (($dept_in_url $dept) || ($dept_in_taxterm $dept));

So, what’s happening?

$dept_in_url = arg(0)

arg(0) holds the first url argument. In my case, the url would be /nl/IT/foo/bar, and arg(0) would be “IT”, not “nl” (see behavioural remarks, below).

if (arg(0) == ‘node’ && is_numeric(arg(1)))

returns true if the url follows the pattern /node/n where n is a numeric node id.

$my_terms = taxonomy_node_get_terms($current_nid);

get all terms associated with current node

sort($my_terms);

I kept getting an array with 1 element but the term object would have a random index (1, 7, 16, ...), so I sort the array to make sure the term object has index 0

$my_terms[0]->name

the first taxonomy term associated with the current node

Behavioural remarks

  • it seems omitting php tags or writing invalid php code results in an unconditional TRUE being returned. Meaning your block will always be shown
  • it seems that introducing some specific kinds of php errors will bork your drupal instance, forcing you to edit the php snippet directly in your database. Example: using $arg(0) when you meant arg(0).
  • arg() returns the node’s original url arguments. This means any language argument that may have been prefixed through i18n is disregarded.
    Also note that url aliases and clean urls are also disregarded by arg(). Check out the comments to Lullabot | hacking phptemplate for a solution to this problem.
  • tip: you can test/debug the snippet code by adding it between html comments in your page.tpl.php file.