Drupal 6: Showing a block conditionally based on the node type of the page

I recently created a block view that I wanted to include only on pages of a certain node type. I decided to create a PHP function that returns true or false based based on the page URL and then call the function via the “Page specific visibility settings”, on the block edit screen.

This function returns true or false based on the what type of node the page URL is. I added this function to my template.php file, but you could add it to a module if desired.

function _MYTHEME_MYBLOCK_visibility() {
  // look up the system path from the page URL
  $path = drupal_lookup_path('source', $_REQUEST['q']);

  // check if the page is a node
  if (substr($path,0,5)=='node/') {
    // load node
    $node = node_load(substr($path,5));

    // check if node exists
    if (!$node) return false;

    // check node type
    if ($node->type == 'MYNODETYPE') return true;

  } else {
    return false;

Then I added a PHP snippet in the “Page specific visibility settings” on the block edit screen:

if (function_exists('_MYTHEME_MYBLOCK_visibility')) return _MYTHEME_MYBLOCK_visibility();
return false;

Now the block only shows on pages of “MYNODETYPE”.