Friday, September 12, 2014

How to make a template file for your custom content type in Drupal 7

So far, all the sites I have made in Drupal (both of them hehe), have had numerous content types, and each node of that type needs to be displayed in it's own theme. By default, it seems, Drupal doesn't have this functionality built in, but luckily it's not hard to add.

Let's say your content type is called "Products" - naturally you would want to name the page template for that content type something like page--products.tpl.php - but without the little hack below, that won't work.

So, to get that to work, make sure you have a template.php file in the root folder of your theme, and then add this code to it:
<?php 
    function nameofyourtheme_preprocess_page(&$vars)
        {
            if (isset($vars['node']->type))
            {
                $vars['theme_hook_suggestions'][] = 'page__' . $vars['node']->type;
            }
        } 
?>
Just put the name of your theme in the nameofyourtheme part above (same name as the folder your theme is located in) - this file might have other functions as well, so just add this to the file if it does...

Now, your page--products.tpl.php template will start working and doing its magic.

No comments:

Post a Comment