Drupal Multimedia

By Aaron Winborn
    Advance your knowledge in tech with a Packt subscription

  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies

About this book

Adding and handling multimedia in Drupal, such as images or video, requires the use of many contributed modules, and deciding which ones to use and how to get the most from them is often not a straightforward task.

This book will guide you through the steps necessary to add image, video, and audio elements into your Drupal sites. The book will take you through the contributed modules for handling media, showing you what they do, when to use them, and how to get the most from them. When contributed modules aren't enough, you will see examples of custom Drupal development to add that special touch to your media.

Publication date:
October 2008


Chapter 1. Introduction and Overview

Drupal is an open-source Content Management System (CMS), which can be used to create powerful, flexible websites that are easily configured and edited by the end users, who don't even need to know how to use HTML to harness its power. Using contributed modules to provide specialized functionality, you can use Drupal to create nearly any site that can be envisioned. Being scalable, it can be used to power anything from a community portal to a corporate network.

Drupal is the framework of choice for tens of thousands of developers and companies that build their sites based on Drupal. Drupal has been consistently rated among the top CMSs for several years.

Released as an open-source project in 2001 by its original creator, Dries Buytaert (http://buytaert.net/), it quickly attracted a strong community of developers and programmers. By now it is a mature and stable product that continues to evolve. With the release of Drupal 6 earlier this year, it remains a cutting-edge choice for website development.

Drupal is a database-driven dynamic web application built on PHP. As PHP is offered by most web hosts, as are MySQL and PostgreSQL, the database management systems supported by Drupal can be deployed from most server environments.


PHP is a reflective programming language, which means that a Drupal script can observe and modify itself at runtime, allowing advanced features such as custom dynamic blocks and its template theming system.

Also, Drupal encapsulates the database in an abstract layer so that the contributed modules may access data stored on the server without knowing the implementation procedure. This allows a site to be deployed from any of the wide array of servers, using MySQL or PostgreSQL, Apache or IIS, Linux or Windows, and many other options.


Drupal has sometimes been criticized as not following Object-Oriented Programming (OOP), largely because it doesn't make much use of PHP's object classes, which is far from true. In reality, Drupal standards implement OOP in an advanced and efficient way (see http://api.drupal.org/api/file/developer/topics/oop.html/6 for more discussion on this topic). Additionally, PHP 5 offers better OOP support and as Drupal moves to the requirement of this version of PHP, module maintainers will take more advantage of it.

The end result is that a site built with Drupal can be expanded and enhanced, using plug-in contributed modules and custom themes to create a powerful and unique site. It is specifically these two facets (contributed modules and custom theming) that will be explored in detail throughout this book, obviously with an eye towards multimedia.

Because of the limited space and the availability of excellent resources, this book assumes you have some basic experience of using Drupal, and that you already know how to install it on a server. In fact, to get the most out of this book, you probably want to have a test installation to test some of the techniques and ideas presented here. Besides visiting Drupal.org, you can also find more help in the Resources Appendix of this book.

Drupal's Multimedia

The Internet has literally exploded with multimedia over the past few years. We will specifically study images, audio, and video in this book, with some additional discussion of interactive media such as FLASH.

Drupal is well-suited to handling multimedia with its modular structure. However, at first glance on installation, this may not seem to be true. This is by design. The core of Drupal is meant to be fast, light, and scalable. It needs functionalities such as asset management and multimedia display that are provided by contributed modules, which must be added onto its core by developers and administrators. Finally, theme developers (or Themers, as these people are commonly referred to in the world of Drupal) take the resultant display and change it to meet the specifications for the site, matching content to compositions.

Due to the dichotomy between the light feel of Drupal core and the overwhelming dread of scouring through hundreds of contributed modules, the need has arisen for a book such as this, which will demonstrate how best to create a site that harnesses the power available for multimedia handling. But firstly, we need to understand the basics offered by the Drupal core and a few essential modules.


Drupal's Multimedia

The Internet has literally exploded with multimedia over the past few years. We will specifically study images, audio, and video in this book, with some additional discussion of interactive media such as FLASH.

Drupal is well-suited to handling multimedia with its modular structure. However, at first glance on installation, this may not seem to be true. This is by design. The core of Drupal is meant to be fast, light, and scalable. It needs functionalities such as asset management and multimedia display that are provided by contributed modules, which must be added onto its core by developers and administrators. Finally, theme developers (or Themers, as these people are commonly referred to in the world of Drupal) take the resultant display and change it to meet the specifications for the site, matching content to compositions.

Due to the dichotomy between the light feel of Drupal core and the overwhelming dread of scouring through hundreds of contributed modules, the need has arisen for a book such as this, which will demonstrate how best to create a site that harnesses the power available for multimedia handling. But firstly, we need to understand the basics offered by the Drupal core and a few essential modules.


Drupal's Building Blocks

There are many essential components of Drupal. The basic components that we'll cover in this chapter are Nodes (content), Regions (areas of a page), Blocks (information placed in a specific region), Themes (describing how content is displayed), and Modules (adding new capabilities to a site). There are other essential components such as Users (providing individual accounts on a site), Filters (to filter user-generated content such as removing unwanted markup), and Comments (added to nodes by multiple users), but they are out of scope for this discussion (though may be touched upon in relevant sections throughout the book).


Most content in Drupal is stored in the form of nodes. In general, if you are new to the concept, you can begin by thinking of a node as what would normally be thought of as a blog, post, or article in more static sites. The reality is that nodes can be far more complex yet flexible than this and may be extended in novel ways, as we'll explore throughout this book:

All nodes have an associated node type. This can be defined by a module such as the built-in page and blog types, contributed image, or video node types. In addition, using Content Construction Kit (CCK), you may define your own custom types and store specific information based on the needs of your site. We will explore this soon.

The basic node will have a title and a body. In general, the body will store the text, although it can be used to display multimedia in line with the text. Modules may allow other types of data known as fields, which may display a set type of multimedia in a specific place in the content, for instance. In addition, some modules such as Image attach may allow multimedia or other data to be attached to any node type.

Nodes are usually displayed in one of these three ways: as teasers, as full pages, and in views. There may be other ways of displaying node content, especially when writing custom code, but we will explore these options, which should suffice in most of the cases.

Teasers are generally smaller or shorter versions of the full content. For instance, a teaser might display the first paragraph or two with a thumbnail. On a basic default Drupal installation, once you have created some nodes, you will see an example of teasers on the front page of the site. By theming, developers may alter how a teaser is displayed.

All nodes may be viewed in full at their respective node pages, usually accessed by clicking on the title of a teaser. By default, this will display all the data stored in a node, although that may be overridden or altered in any of several ways.


The URL for the default node page view will always be at /node/[nid], replacing [nid] with the node's unique identification number. This URL may be overridden manually or with other modules such as by using the URL path settings section of the node submission page or automatically using the Pathauto module. But it will still always be accessible using /node/[nid], for example at http://www.example.com/node/225 or http://www.example.com/?q=node/225 (if not using clean URLs).

Throughout this book, when displaying a URL, we'll assume you have enabled clean URLs on your site. If you have not, you would need to prepend ?q= to a URL. For example, /admin/build/modules would be ?q=admin/build/modules. In both cases, that would be local to your site such as http://www.example.com/admin/build/modules or http://www.example.com/?q=admin/build/modules. To enable clean URLs on your site, browse to Administer | Site configuration | Clean URLs at /admin/settings/clean-urls or ?q=admin/settings/clean-urls.

The Views module (touched upon later in this chapter) opens up many new ways of displaying information from nodes. Views may display nodes as teasers, full views, or slide shows, or may take specific parts of the data and display them in a list or

a table. There are many other ways a view can display content and we will explore the more common methods in this book.

Regions and Blocks

A page is divided into several regions, each of which can be used to display content using blocks. By default, the main content of a page is displayed in the content region.For instance, the node content when displaying a node's page or the listing of recently published and promoted nodes on the front page. The left sidebar on a default Drupal installation is another region, as are the header, footer, and right sidebar.


Custom regions are easily added to a theme by modifying that theme's .info file. For instance, you might specify regions[content_top] = content top to create that new region. Note that this is different than in Drupal 5, where new regions were defined in a now deprecated mytheme_regions function. We'll explore theming in more detail throughout the book.

You may determine what content will be displayed in what regions on the Blocks administration page by browsing to Administer | Site Building | Blocks (at /admin/build/block). Active blocks are shown here grouped by region, with the remainder shown in the Disabled section of the page.

After setting a block into a region, you can further determine its placement in the region by dragging and dropping it. Finally, by clicking on the configure link next to a block, you may change block-specific settings such as controlling what pages a block will be displayed on, or changing the block's title:

Drupal and installed modules will define many useful blocks of information such as a listing of users who are currently online (Who's Online), or the main Navigation menu. You may create custom blocks (using the Add block tab on the Blocks administration page) where you can add static text or even a short PHP script (assuming you've enabled the PHP filter module) for something dynamic. Using the Views module, you may also create blocks listing nodes that are filtered and sorted by your own criteria.


Most developers will want to format the content of their site in a manner that is different from what comes out-of-the-box. We will cover some of these methods in detail throughout the book. This is referred to as "theming", and many Drupal developers specialize as themers.

As an administrator, you may have noticed the theme section of the site. At Administer | Site building | Themes (at /admin/build/themes), you will see several themes that are available. These may be themes that are included with Drupal, contributed themes available from Drupal.org or other sources, and/or custom themes created specifically for the site:

It is this third possibility of custom themes that will be of most interest to us during the course of this book. So we will need to know the basics of overriding a theme. If you are interested in learning the theming techniques that will be covered, you

should probably have a custom theme to play with. For most of the examples in this book, we'll modify a copy of the Garland theme that comes shipped with Drupal and is enabled by default.

Contributed Modules

We will make much use of the various contributed modules throughout this book. Some of these modules, such as Image and Embedded Media Field, are specialized enough to be covered in their relevant sections. Others, such as the Content and Views modules, are essential throughout several sections. We will examine them in this chapter and explore them in more detail as needed later.

One of the strengths of Drupal is its expandability using contributed modules, and no single book could fully cover more than what many might consider the most essential, let alone the hundreds of currently available modules. This is especially so because new modules are constantly being added and old modules updated.

The modules presented in this book have been selected based on their relevance to the required tasks, their code stability, and high level of support and maintenance. All of these modules are used in production to power sites that may be small or large, and have sometimes dozens or hundreds of volunteers actively troubleshooting and maintaining them.

As you continue to explore the world of Drupal, make certain to continuously examine the available contributed modules. You can find nearly all of them at http://drupal.org/project. You can further find ongoing discussions of the development and use of the modules at http://groups.drupal.org/ in various discussion groups.


You may also be interested in visiting the third-party site Drupal Modules at http://drupalmodules.com. This site allows user reviews and ratings, allowing you to read feedback about a module before choosing to install it. Such a metric, though not failsafe, can be useful when considering the hundreds of currently available modules.


Content Construction Kit (CCK)

The CCK module is a valuable contributed module that can be found on a large majority of Drupal sites. In fact, parts of it are increasingly becoming integrated into Drupal core because of its power and versatility.

As discussed earlier, content is largely defined on a site by content types for nodes. For instance, modules may be activated to provide blog, page, or video-type nodes. Using CCK, you can also define custom types for a specific purpose.

As an example you might define an article content-type, which in addition to the title and body fields automatically provided, might include a byline field, a teaser Image, and an issue reference.

As with all contributed modules, you will first need to download and install the module before using it on your site. The CCK module is available at http://drupal.org/project/cck. Once downloaded, you will need to place the entire extracted folder in the /sites/all/modules directory. After this, you will see the module along with all other available modules for a site by browsing to Administer | Site Building | Modules (at /admin/build/modules ).

Enable that module and any other desired modules included in the CCK package of that screen such as Text, Number, or Node Reference. (In Drupal 5, that section is named Content.)

Custom Content Types

Now you will be able to create your own custom content types. Continuing with the example of an Article type, you would browse to Administer | Content management | Content types | Add content type (at /admin/content/types/add) and fill in the appropriate fields on that page. After submitting, you would have a new content type with a title and an optional body:


The strength of CCK is that it allows custom fields to be defined and added to the content types. Fields allow you to add any additional information to a type such as subtitles, images, and videos. Some basic fields, such as text and numbers, are included with the module. But others, such as images and files, require additional contributed modules.

To add fields, you will need to click on the add field link next to the new type on the resulting page from our ongoing example:

In this example, that would bring you to /admin/content/node-type/article/add_field). You'll name the field, select the type of field such as text or image, and submit the page to see the configuration page for the field. Here you can further define things such as setting a maximum image resolution or allowed values. In this example, we'll create a text field named Subtitle:

The resulting page contains sections that will affect the specific field. Additionally, because created fields can be shared among content types, you can further define settings that will affect all similarly shared fields.

Once a field has been created, you may change the order of its display by dragging the icon to the left of the field on the resulting page, which you can also find by browsing to Administer | Content management | Article | Manage fields (at admin/content/node-type/article/fields ):

User Permissions

We can define permissions for our users, who can be grouped by roles. For instance, we might have an edit role, whose users are able to create article content. First, we'll define a new role by going to Administer | User management | Roles (at /admin/user/roles ):

You would then visit the User Permissions settings browsing to Administer | User management | Permissions (at /admin/user/permissions), where you can set permissions for various roles such as allowing editors to create article content. You will see the permissions for all content types under the node module section of the form.


In Drupal 5, the Permissions page was known as Access Control, and could be found by browsing to Administer | User management | Access control (at /admin/user/access).

To give a user the new role, we would then need to edit his or her user account. We can find a list of recent users at Administer | User management | Users (at admin/user/user), where we can edit them:

Creating Content

Once you have created a new content type and set its permissions, you may create new content of that type by browsing to Create content and clicking on the new type (in this case at /node/add/article ):



Views is another contributed module that is found on many Drupal sites. It is used to create custom listings of nodes that are filtered and sorted using unique criteria, and displayed in pages and/or blocks as needed.

These views may be replicated in other ways such as by using custom SQL queries. But most developers and administrators will probably find the administration forms used to build a view much easier to manage, particularly for complex arrangements.

A view can take data from many sources such as specific fields of nodes or user information, filter them for desired criteria, and sort them in nearly any order. The Views and other contributed modules expose several default views that may be activated and overridden on a site. For instance, you might override the default front page view to display only promoted nodes of an article content type.


If you are familiar with Views from Drupal 5, you will be pleasantly surprised by Views 2 for Drupal 6. The engine has been rewritten from the ground up, allowing for new features such as creating views from data other than nodes. Additionally, the User Interface (UI) has been completely revamped using AJAX. This means the information you need when administering a view is all in one place, with a system of tabs and drawers to sort and access it, rather than the older system of collapsible field sets. If you are building a view for Drupal 5, the steps outlined here are largely the same, but the UI is considerably different.

View Administration

As with the Content module (and all other contributed modules), you will need to first upload the module directory into the /sites/all/modules folder. The Views module is available at http://drupal.org/project/views. Once present, you will activate it at Administer | Site building | Modules (at /admin/build/modules). On that page, you'll note that several other related modules are also available in the Views package. For the examples in this book, you will need at a minimum to activate Views and Views UI.

When you browse to Administer | Site building | Administer views (at /admin/build/views), you will see the system default views interspersed with any custom views you've created:


If you have a lot of views on your site, you may control the order on this page with the drop-down selection filters at the top of the screen. Additionally, you may enter an optional View tag when initializing the view, which will allow you to sort them by functionality on the administrative screen.

Creating a New View

You can easily create a new view from scratch by clicking on the Add tab, which brings you to /admin/build/views/add. However, for this example, we're going to clone an existing view so that we can see how they're set up while building it.

Click on the Enable link to the far right of the frontpage view. This enables the view on your site. Then click on the Clone link associated with that view, which will show you how the front page is created by default. You will be brought to the Clone view frontpage page (at /admin/build/views/clone/frontpage ):

On the resultant screen, you'll be able to change the name and description of your new view and the tag, if desired. Although you can't change the type when cloning a view, when creating a view from scratch, you'll be able to select one of many View types such as Node, Comment, or User. This means you can create a view that is a listing of users just as easily as a listing of nodes or comments.

Change the name to articles_recent and describe the view appropriately. If you like, you can change the View tag to articles, to make sorting views easier in the future. Then click Next:

Basic Settings

On the left of the configuration screen, you'll see drawers for Defaults, Page, Feed, and some form elements to add new displays and analyze our view. By clicking on each drawer in turn you'll be able to see the different displays for our view, each of which can override the defaults to format a view in a specific way.

TheBasic settings section controls things such as the Title displayed for the view, the Style to display the data, for example, a List or Table, the number of Items per page, who can Access a particular view, and similar items. We'll leave these alone for now.

Using the Filters section on the right, we can specify which nodes will be returned for our view. In this particular case, we want to filter nodes by their type, as we only want to display the Article nodes we created earlier:

Press the "+" button next to Filters to add a new filter. This will show all available filters. We can select Node from the Groups selector to make it easier to find the Node: Type box, which we will select before pressing Add.

The section will be replaced with further options to specify how to filter the view. We will select our Article type and press Update here:

Next, click on the link for Node: Promoted to front page and then press the Remove button, as we want this view to retrieve all articles, regardless of whether they have been promoted.


If you expose a filter, then it will also show up under Exposed Filters, where you may set further options. Exposed filters will be displayed at the top of a view, allowing the user to set those options to determine which nodes to display.

Finally, change the title (in the Basic settings) to Articles by clicking on None, entering the new title in the new text field below, and pressing Update.

Page Views

Now we'll set up the page. Click on the Page drawer to the left, just below Defaults. This section will determine how the view is selected and displayed as a page, in this case from /frontpage, as seen in the Page settings section:

Click on frontpage next to Path within Page settings, and change the path to articles. After you press Update, do the same for the feed by visiting the Feed drawer and changing the path from rss.xml to articles/rss.xml:

Then you can select Block from the selector above Add display, and press that button. This will create a new display for the view similar to Page and Feed. The only changes we need to make there are to set it to four items per page, rather than the default of 10, add a More link (which will allow users to click through to the page when there are more than four items), and to turn off the pager.

When doing each of these, we'll need to override the default values by clicking on the Override button that will appear in the information area (which will add the message Status: using overridden values above that area).

You may then Save the view, so we can see the results.

Advanced Views Options

The Arguments fieldset is used to create some flexibility from the URL. Thus, by setting the arguments here, you might have a gallery of all recently posted videos with a URL of /videos, and further display of only videos in a certain vocabulary with /videos/[vocabulary-id], and finally only videos in a certain taxonomy term with /videos/[vocabulary-id]/[term-id]. Note that if there are Arguments set for the view, then those will be combined with Filters when selecting the nodes to display.


The Sort criteria will determine the order to display the selected nodes for the view. The frontpage and article views will first display nodes marked as sticky, and then set them in reverse order of creation time. We could easily change the order, for instance by sorting articles by popularity, author, or time of most recent comments.


Advanced Theming

Because overriding the display of default content is essential in creating a professional site, we'll explore a few techniques that any serious developer or themer should keep in a toolkit. Template files are used to separate PHP code from the HTML, which is more familiar to many themers and designers. Sometimes we need to create custom regions, which also we will explore. And finally, we need to know how to override specific content at its most basic element, the theme function.

Adding a New Theme

It is certainly possible and sometimes preferable to start a new theme from scratch. However, for this book, we'll modify an existing theme to give ourselves a jumpstart.

From your FTP client, you'll need to make a copy of the Garland theme directory. You'll need to copy the entire Garland directory from /themes/garland to /sites/all/themes. Then rename the new Garland directory, for example to mytheme. This folder name will be used as the machine name of your new theme.

If you don't already have a themes directory in /sites/all, you'll need to make one first. When checking for themes, Drupal will look in the appropriate site directory such as /sites/example.com/themes. Then it will look in /sites/all/themes, and finally in the root /themes directory.

By placing contributed, custom, and overridden themes in the /sites directory, you can accomplish several things. First, it will override a theme in the root /themes directory. Secondly, if it is placed in /sites/all/themes, it will be made available to sites sharing the same codebase. (Conversely, it will only show up for a specific site if it isin something like /sites/example.com/themes.) Finally, it will be easier to update the site as Drupal evolves, since you will be able to simply update to a later version of Drupal without worrying about theme overrides in the root directory.


As you may have noticed from this example, Drupal allows multiple sites to share the same codebase. In such a case, each site would need its own subdirectory within the /sites folder such as /sites/example.com for http://example.com, or /sites/mysite.com for http://mysite.com. Any further subdirectories within that folder will be made available only to that site. Additionally, multiple sites may even share the same database, assuming that they have separate database table prefixes specified in the Advanced options section during installation.

You will also need to change the garland.info file to mytheme.info (or whatever name you have chosen). Also, edit that file and change the line that reads name = Garland to read something like name = My Theme. (You will not have a .info file for your theme in Drupal 5, so this will not apply in that case.)

After creating your new folder and making the necessary changes, you will browse to Administer | Site Building | Themes (at /admin/build/themes) on your site and enable the theme. You will also make the theme the default and disable the other themes. However, you may wish to keep another theme (such as the original Garland) as the default theme during the development and instead set the new theme on your user account edit page.

Finally, you may wish to keep a different theme layout for administration pages, particularly if your theme will not lend itself to the wide tables sometimes seen on those pages. In that case, you will browse to the Administration theme settings page at Administer | Site Configuration | Administration theme (at /admin/settings/admin) and set it to something basic like Garland.

Once you have enabled your new theme, you'll be ready to begin development on it. This is largely achieved by writing template files, which are contained in the theme directory and end with .tpl.php in their filenames. We will cover the basics of this in the template files section of this chapter, and in more detail throughout the book.


As the Garland theme it is installed by default on every new Drupal installation, we have chosen to use it throughout this book. But when developing a site for production, you may wish to start from another theme or even entirely from scratch. You can see many contributed themes for Drupal at http://drupal.org/project/themes. Additionally, you can see live previews of many of those themes at The Theme Garden (at http://themegarden.org/). Finally, consider the Zen theme, available at http://drupal.org/project/zen, which is meant to offer a no-frills, standards-compliant base theme. You may find its excellent documentation and growing community of developers and themers to be most suitable.

Basic Template Files

By default, Drupal uses PHPTemplate to power its themes. This flexible and powerful engine allows themers to wrap specific content in HTML snippets contained in specific files and functions. Themers can do all their work without knowing how to program, but if they are willing to explore the world of PHP, they have all the power of that scripting language to bring to bear on their themes.


There are other engines available for Drupal, notably Smarty theme engine, which use Smarty Template Engine syntax. However, this book assumes you are using PHPTemplate.

At its most basic, a theme will contain a page.tpl.php file. This file will wrap all the content to be displayed in the required HTML tags to feed to the user's browser. Several PHP variables are made available for theming, which generally contain either content to be displayed or directives to tell us how to display content.

Also, a theme folder will contain one or more stylesheets such as Garland's style.css, which is the basic stylesheet to be used by that theme. The theme's .info file will contain a list of stylesheets to be included on a page. We will explore Cascading Style Sheets (CSS), which are necessary to control the output of our media.

Nodes are generally displayed using special template files in the themes folder. In addition to the default node.tpl.php, each node type may have its own template file, which will be used to wrap node content when provided. These are named by appending the node's machine-readable name to the filename. For instance, we might have a node-image.tpl.php file to wrap Image nodes, node-external_video.tpl.php for a custom External Video node type, and node-article.tpl.php for the Article content type we created earlier.

The template.php file contains functions made available to the theme, many of which are used to provide files to override the default theme functions offered by Drupal modules. This is an important concept that will be explained soon.

Other template files may be created in this folder to override how content is displayed. For instance, block.tpl.php and comment.tpl.php will respectively wrap blocks and comments with HTML. Any theme function available in Drupal may be overridden in this fashion, although some more obscure functions will require more of an understanding on how content is created in Drupal. Fortunately, there are tools available such as the Theme Developer Module (which we'll see in Images for Themers, chapter 4) to make this task easier.

Custom Regions

So you've created a new theme as outlined in the Themes section earlier. You've explored the files there, and are ready to begin overriding your theme.

One of your first tasks might be creating custom regions for blocks. Let's say you want a new block above the main content where you'll highlight articles and videos on the front page.

By default, you already have a content region. However, any blocks you activate in this region will be displayed below the page's main content.

This requires that you override your theme's region. To do this, you will need to edit the theme's .info file, in our case mytheme.info.

You will need to redefine all your regions, and enter your new region(s) by adding the following to the file:

	regions[left] = Left sidebar
	regions[right] = Right sidebar
	regions[upper] = Upper
	regions[content] = Content
	regions[header] = Header
	regions[footer] = Footer

In order to register this change (or any change in the info file), you will need to visit Administer | Site building | Themes (at /admin/build/themes). Also note that you must enter all the desired regions when adding a new one even if the defaults are not listed originally in the file, as an override to the regions will remove the defaults entirely. For instance, if we were only to add regions[upper] = Upper, then only that region and the content would appear on a page with none of the other desired regions.


As themes in Drupal 5 don't have an info file, you would need to invoke the region's hook for the theme, in this case by creating a mytheme_regions function. See http://drupal.org/node/29139 for more information.

This will make any new regions available to Drupal, in our case creating an additional region labeled upper. The keys on the left of the array ('upper', 'right', and so on) define the variable names for the regions in your page.tpl.php file. The values on the right side Upper, Right sidebar, and so on will be the names for the regions as displayed on the Blocks administration page.

Once you have defined your regions in the template.php file, you need to also make sure that any new regions are displayed in the page.tpl.php file. You'll be able to display a region simply by printing its associated variable (as defined in the region array). For instance, our new upper region will be displayed by printing the $upper variable.

If you are following this example and have overridden the Garland theme, then next you will find the text <?php if ($breadcrumb): print $breadcrumb; endif; ?> in the file. Now add the following just below it:

	<?php if ($upper): ?>
	      <div id="upper">
		<?php print $upper; ?>
	<?php endif; ?>

This will ensure that the upper region is displayed only if there is a value in that variable, which will only be true if you set blocks to display in that region. It will further enclose this region in a unique HTML div that may be customized using the CSS stylesheets.

You will be able to add blocks into this region from Administer | Site building | Blocks (at /admin/build/block). This new region will appear below the breadcrumb on a page, but before any help messages, titles, content, and so on:


You may notice the combination of PHP code within <?php ?> and HTML (such as <div></div>). This is one of the strengths of PHPTemplate. It allows a themer to work with the familiar markup of HTML to easily insert useful snippets of code or to print PHP variables within the markup. Within the template (.tpl.php) files, you need to ensure that all PHP code is contained within <?php ?>.

Theme Function Overrides

Any content provided by modules in Drupal may be overridden in the theme. If you know in general what theme function is creating the content, you will also know the template file or function to create.

For instance, if you want to display individual comments with reply/edit/delete links just below the comment's title rather than after its content, you would edit comment.tpl.php in /sites/all/themes/mytheme to move the code printing the links to just below the title line, so it reads:

	<h3><?php print $title ?></h3>
	<?php if ($links): ?>
	        <div class="links"><?php print $links ?></div>
	<?php endif; ?>

Often you may wish to override a theme that is not provided as a file in the default theme. In these cases, you will need to find the function in the code, and either create a template file (tpl.php) for the markup or create a theme function override in template.php. In some cases, especially for a short snippet of code, it may be easier to create the theme function override. If you make it available as a tpl.php file, this may be easier for themers to work with, particularly if they don't have much coding experience. Also, some theme functions may be more suitable in that format such as when they create a lot of markup in their output.

This is suitable for a theme function override and, in fact, is already available in Garland's template.php. The code for this follows after first searching the Internet to see that the HTML character code for» is &raquo;. Simply rewrite the included function as follows:

	function phptemplate_breadcrumb($breadcrumb) 
	    if (!empty($breadcrumb)) 
	      return '<div class="breadcrumb">'. implode(' &raquo; ', $breadcrumb) .'</div>';


The» character is officially known as a guillemet, or right angle quote. It is used to demarcate quotes in French and other languages.

Our next request is to change the text that reads Comment viewing options above comments to read Comment Controls. (Comment viewing options are set by browsing to Administer | Content management | Content typesadmin/content/types and selecting the content type to configure. In Drupal 5, they're set globally at Administer | Content management | Comments| Settingsadmin/content/types

Garland has no built-in override for comment controls, so we'll need to hunt through our code to find this. We know that comments are displayed using the comment module, which is found in the /modules/comment directory. So we open the comment.module file in our editor. Searching for the text Comment viewing options, we see the output is generated with the theme_comment_controls function.

To override a theme function, we simply rewrite our new function in template.php, replacing the theme_ in the function name with phptemplate_. So for this example, we will copy the code from the function, place it in template.php in our new theme directory, and make our changes:

function phptemplate_comment_controls($form) {$output = '<div class="container-inline">';
$output .= drupal_render($form);
$output .= '</div>';
$output .= '<div class="description">'. t('Select your preferred way to display the comments and click "Save settings" to activate your changes.') .'</div>';
return theme('box', t('Super-Duper Comment Controls'), $output);


Important note: When overriding theme functions, you must register new changes in the database (as of Drupal 6). To do so, you will either need to clear your cache (the easiest method being to install the Devel module from http://drupal.org/project/devel and use its provided links) or run the drupal_rebuild_theme_registry() function. While developing a theme, you may choose to add that function to the top of the template.php file, so it is run every time a page is loaded. However, if you do this, make certain to remove it before moving the site into production.

You could also have named this function something like mytheme_comment_controls. In fact, though the Garland theme doesn't follow this advice, the official policy is to do that and avoid conflicts when using sub-themes. However, there is also a strong case for using a phptemplate_ prefix. Using the phptemplate_ prefix makes your theme more portable. So if you later change the name of the theme or copy it to another directory for further development, you won't need to change all your mytheme_ references to newtheme_.


A useful online reference is the Drupal API found at http://api.drupal.org. From here, we can find definitions for all core functions, as well as topics of specific interest such as http://api.drupal.org/api/group/themeable/6.

Template Files Revisited

Some theme functions lend themselves well to being overridden using a template (.tpl.php) file. Our emboldened editor now asks us to make some overrides to the forum page, so that the link that says Post new Forum topic is repeated at the bottom of the screen.

All modules (as of Drupal 6) must register their themeable functions using a hook_theme function. This means that you can scan that function to quickly find themes that may be overridden.

Thus, we read the forum_theme function at http://api.drupal.org/api/function/forum_theme/6 and see the following:

'forums' => array('template' => 'forums',
'arguments' => array('forums' => NULL, 'topics' => NULL, 'parents' => NULL, 'tid' => NULL, 'sortby' => NULL, 'forum_per_page' => NULL),

This looks promising, so we look up theme_forums at the Drupal API. However, it turns up nothing, so we double-check by searching for that function in the forum module. No luck!

It turns out that modules (starting with Drupal 6) may also define their own template files. Knowing this, we scan the forum module directory at /modules/forum and discover several template files there, including forums.tpl.php.


Note that if you're using Drupal 5, you would actually need to override theme_forum_display, which turns out to be a trickier business involving the use of the obsolete _phptemplate_callback in template.php. See http://drupal.org/node/11811 for more information.

Finally, we copy forums.tpl.php to our theme directory and override it as follows, duplicating our links:

<?php if ($forums_defined): ?><div id="forum">
<?php print theme('links', $links); ?>
<?php print $forums; ?>
<?php print $topics; ?>
<?php print theme('links', $links); ?>
<?php endif; ?>



We now have enough basic knowledge to begin integrating multimedia in our Drupal sites. We have learned about Nodes, which are the basic building blocks for content. We discovered that several contributed modules, including the invaluable CCK and Views modules, may be used to create and format our content. We now know that blocks are displayed in regions, and that themes control all the output of a page. We have further learned that any theme function in Drupal may be overridden at the theme level, using either a direct override (with a phptemplate_ or mytheme_ function), or in many cases by creating a template file ending with tpl.php.

In the next chapter, we will delve into the rich world of images.

About the Author

  • Aaron Winborn


    Aaron Winborn has been developing websites since the mid-90s. Beginning as a freelancer while teaching at a Sudbury school (a democratic and age-mixed model for young people), his clients demanded more and more features, until he (like everyone and their grandmother) realized he had built a full-featured content management system that required more work to develop and maintain than he was able in his spare time.

    He realized at some point that somewhere in the world of Open Source, someone had to have created and released something to the community. Of course, the wonderful news was Drupal.

    After converting the existing sites of his clients to Drupal, he continued learning and began to contribute back to the community. About this time, Advomatic, a company with similar interests and a commitment to the Drupal community, began expanding beyond the initial partners who formed it in the wake of Howard Dean's presidential campaign of 2004. Aaron realized that his own goals of creating great sites with a team would be better matched there, and he was hired as their first employee.

    Since that time, he has helped to develop some excellent sites, with clients such as Air America Radio, TPM Cafe, NRDC, Greenopia, Mountain News, Viacom, and Bioneers. He has also contributed several modules to Drupal, mostly stemming from his work with multimedia, including Embedded Media Field (for third-party Video, Audio, and Images), Views Slideshow (to create slide shows out of any content), and the RPG module (for online gaming, still in progress).

    Browse publications by this author
Book Title
Access this book and the full library for FREE
Access now