Drupal - node.tpl.php by Node Id

Kevin's picture

[b]Q:[/b] How can I override my theme's node template file, node.tpl.php, just for one specific node id?
[b]A:[/b] In your theme, override [i]phptemplate_preprocess_node()[/i] and provide a template suggestion for 'node-[nodeId]', and then flush cache.

It is easy to provide an alternative [i]node.tpl.php[/i] template for your different content types by naming your new node template file along the lines of node-[nodeType].tpl.php, placing it in your theme folder and then clearing you cache. Drupal automatically handles all of this for you.

But how can you provide an alternative node template file for just a single node instance, e.g. for node id 22, just adding a template file named node-22.tpl.php doesn't work?

By default drupal does not handle this, but a solution can be found here, in the comment by psynaptic:

http://drupal.org/node/190815

The solution involves overriding [i]THEME_preprocess_node()[/i] and manually providing drupal with a 'template suggestion'. Just place the following code into your theme's [i]template.php[/i] file remembering to replace 'THEME' with the name of your theme (or 'phptemplate'). [i]template.php[/i] will be found in your theme's folder:


/**
* Override or insert variables into the node templates.
*
* @param $vars
* An array of variables to pass to the theme template.
* @param $hook
* The name of the template being rendered ("node" in this case.)
*/
// Replace 'THEME' with your theme's name or 'phptemplate'
function THEME_preprocess_node(&$vars, $hook) {
$node = $vars['node'];
$vars['template_file'] = 'node-'. $node->nid;
}

Remember to flush you cache after making the change!

Now you should be able to create node template files named like node-[nodeId].tpl.php in your theme folder and have them override node display for specific node ids.

Big thanks again to psynaptic for the tip!

Share this post: 

Recent Work

Some of Ireland's biggest brands use Pride Design to Design, Build, Manage, Market and Maintain their websites.

Website design for St.Patricks Credit Union in Dublin, Including Loan Calculators.

Website design and development for a step by step wedding and other stationary ordering website f

New website designed and developed for Cork's newest café, which is based in Merchants Quay in Co

New Website design for Pain Relief clinic based in Cork City.

Website for a busy Dublin city centre pub.

We redrafted the Ballymaloe house website to modernise the look and feel of the site and to also

We revamped the website for the Ballymaloe Cookery School.

We revamped the Cully & Sully website onto Drupal.

Rachel Allen was brought up in Dublin and left home at eighteen to study at the world-famous Ball

Clóna Dairy Products are a Dairy Company based in Clonakilty, Co. Cork, since 1919.

Project Arts Centre is Ireland’s leading centre for the presentation and development of c