showing a block based on url or taxonomy term

Joeri Poesen //

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.

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

	<p>if (arg(0) == ‘node’ && is_numeric(arg(1))) {
  $current_nid = arg(1);<br></br>
}</p>

	<p>$my_terms = taxonomy_node_get_terms($current_nid);<br></br>
sort($my_terms);<br></br>
$dept_in_taxterm = $my_terms<sup class="footnote"><a href="#fn184216864552c9462417e3a">0</a></sup>->name;</p>

	<p>return (($dept_in_url  $dept) || ($dept_in_taxterm  $dept));<br></br></p>

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.