Drupal Tutorials

Drupal theme function overriding

This tutorial requires you have basic to intermediate knowledge of Drupal theming and basic knowledge of PHP is a plus.

For those new to Drupal the term Drupal theming can sound a little scary but really it really isn’t something you should fear!
Drupal theming in its simplest form in just a HTML/CSS layout with a bunch of PHP tags dropped in.

There seems to be a perception that Drupal theming is something really difficult but to be honest if your HTML and CSS skills are up to scratch and you’re open to learning some basic PHP you’ll have no problems.

Drupal can run on different theme engines but as of Drupal 4.7 the phptemplate theme engine became standard, so that’s what we’ll focus on in this tutorial.

What is a theme function?

A theme function is a PHP function withing Drupal that is prefixed with theme_. Theme functions display HTML, and which can be customized by themes.
This is how Drupal.org defines a theme function:

All functions that produce HTML for display should be themeable. This means that they should be named with the theme_ prefix, and invoked using theme() rather than being called directly. This allows themes to override the display of any Drupal object.

How do theme functions work?

Next we’ll need to understand how and when theme functions are executed. In every page load and number of theme functions can be executed by Drupal.

For example you may have a page listing all of the users on your site and this list would call the function theme_username (that we’ll look at more later) for every user in the list to output the users username as a link. This user list may then be passed to another theme function and then finally the content will be passed to the theme_page function which is automatically used by Drupal in order to display your page content within your themes page template.

Modules declare and generally execute theme functions although you can call a theme function from anywhere in your Drupal site (ie. From your theme) providing the module providing the theme function has been loaded.

The great thing is using our themes template.php file we can override any theme function we like without having to edit a single module and this is where using a template.php file becomes so powerful.

Let me briefly explain what I mean by override. By override I mean declaring a new version of a theme function (in template.php) and completely by passing the original theme function in order to alter its output.

An example

Let’s take a look at the theme_username function to explain how to do a theme function override.

Who's New block outputAs I mentioned previously the theme_username function outputs a given users username, so every time you want to display a users username rather than retype a load of code all you need to do is call this function. The "who’s new" block is a great example of where this function is used (see grab to the right). But let’s say you want to change the output of this function so that every time a username is displayed the users user ID is shown after the username, not hugely useful but should give you the idea. It’s fairly simple we just need to override the theme_username function like so:

  1. Open up your template.php file that can be found within your themes root folder or if you don’t have one simply make a PHP file and save it to your themes root folder as template.php. By root folder I mean where your page.tpl.php is located.
  2. Next open up the theme.inc file located in the includes folder with notepad or whatever text editor you use. This is the file that declares the function we want to override.
  3. Find the function theme_username within the theme.inc code then copy and paste the whole function into your template.php file. You can now also close the theme.inc file as we won’t need it again.
    <?php
    function theme_username($object) {

      if (
    $object->uid && $object->name) {
       
    // Shorten the name when it is too long or it will break many tables.
       
    if (drupal_strlen($object->name) > 20) {
         
    $name = drupal_substr($object->name, 0, 15) .'...';
        }
        else {
         
    $name = $object->name;
        }

        if (
    user_access('access user profiles')) {
         
    $output = l($name, 'user/'. $object->uid, array('title' => t('View user profile.')));
        }
        else {
         
    $output = check_plain($name);
        }
      }
      else if (
    $object->name) {
       
    // Sometimes modules display content composed by people who are
        // not registered members of the site (e.g. mailing list or news
        // aggregator modules). This clause enables modules to display
        // the true author of the content.
       
    if ($object->homepage) {
         
    $output = l($object->name, $object->homepage);
        }
        else {
         
    $output = check_plain($object->name);
        }

       
    $output .= ' ('. t('not verified') .')';
      }
      else {
       
    $output = variable_get('anonymous', t('Anonymous'));
      }

      return
    $output;
    }
           
    ?>
    The theme_username function found in theme.inc

  4. In your template.php file rename the theme_username function to phptemplate_username and save the file. This puts our template.php file in control of the theme_username function and completely bypasses the theme.inc version of the function.

    Before
    <?php
    function theme_username($object) {
    ?>
    After
    <?php
    function phptemplate_username($object) {
    ?>
  5. We can now make any changes to the function we desire and all at theme level so we’re not messing with any modules or themes.
    So let’s go ahead and add the users user ID after their username by modifying the last line of the phptemplate_username function to look like so:
    <?php
      $output
    .= '('. $object->uid .')';
      return
    $output;
    }
    ?>

    So your final phptemplate_username function should look like this:
    <?php

    function phptemplate_username($object) {

      if (
    $object->uid && $object->name) {
       
    // Shorten the name when it is too long or it will break many tables.
       
    if (drupal_strlen($object->name) > 20) {
         
    $name = drupal_substr($object->name, 0, 15) .'...';
        }
        else {
         
    $name = $object->name;
        }

        if (
    user_access('access user profiles')) {
         
    $output = l($name, 'user/'. $object->uid, array('title' => t('View user profile.')));
        }
        else {
         
    $output = check_plain($name);
        }
      }
      else if (
    $object->name) {
       
    // Sometimes modules display content composed by people who are
        // not registered members of the site (e.g. mailing list or news
        // aggregator modules). This clause enables modules to display
        // the true author of the content.
       
    if ($object->homepage) {
         
    $output = l($object->name, $object->homepage);
        }
        else {
         
    $output = check_plain($object->name);
        }

       
    $output .= ' ('. t('not verified') .')';
      }
      else {
       
    $output = variable_get('anonymous', t('Anonymous'));
      }

     
    $output .= ' ('. $object->uid .')';
      return
    $output;
    }
    ?>
  6. Save the template.php file and as you should see something similar to the image below. Et viola you’ve just do your first theme override, pretty simple wasn’t it.
    Who's New block output after

I know that was a very simple example of Drupal theme overriding but hopefully you can see how this same principle can be used to override any theme function with Drupal allowing you to change the appearance of your site without ever having to edit a core file.

In future tutorials I’ll show you how to override the default user profile layout to create a Facebook type user profile layout.

Thanks for reading and please leave any comments below.

Commenting on this Tutorial is closed.

Categories:

Comments (46)

Ohno! Studios's picture

“where your page.tpl.php is located”

Jumping straight in there:

  1. Which files are required in your themes folder when you start on a new theme?
  2. Are these files the same accross all themes, or are they custom?

The reason I’m asking is I’m a designer with HTML & CSS knowledge trying to learn Drupal theming – my PHP knowledge is very limited for now. Even though it might not be complicated the basic step 1, step 2 of starting out a theme is not well documented – IMHO.

*Hmm. Drupal Theme Guide might help. |(


Save the template.php file and as you should see something similar to the image below. Et viola you’ve just do your first theme override, pretty simple wasn’t it.

You only need to put the code in a file called template.php in your theme folder.

When it does not work, try switch to another theme and back in /admin/build/themes. Your new “phptemplate_username” function will be picked up by your theme this way.

The template.php file should be placed in the themes/yourtheme folder, where the page.tpl.php file is.

liked. could do with much figured topics they are obviously PIC18

funnyjenny's picture

many thanks for providing us with this good info to save the template. funny quotes and funny facebook statuses

amedjones's picture

im trying to change the text link of “read more” for the teaser. I grabbed the function from node.module and placed it in template.php but i cant see the changes. But when i did the function directly in node.module, the modification are reflected .. of course this article advices otherwise.

Here the function that i copied and edited

function phptemplate_node_link($type, $node = NULL, $teaser = FALSE) {
$links = array();

if ($type 'node') {
if ($teaser 1 && $node->teaser && $node->readmore) {
$links[‘node_read_more’] = array(
‘title’ => t(‘Endelea’),
‘href’ => “node/$node->nid”,
‘attributes’ => array(‘title’ => t(‘Endelea.’))
);
}
}

return $links;
}

the above code is placed in template.php. Im trying to change “Read more” to “Endelea” ( swahili way of saying read more :) )

DrupalSN's picture

Hi,

You can’t override none theme functions and i don’t think theme_node_link exists, so the above code you mention won’t work.

If you want to translate a string check out:
http://drupal.org/project/Translations
http://drupal.org/project/stringoverrides

Hope that helps
Tom

amedjones's picture

hi thanks for the reply. no theme_node_link does not exist. This function is in node.module which im guessing cannot overriden because its a core module?

thanks for the link, Translations is not supported anymore but stringoverrides worked great :)

dosensocial's picture

Hi is a good tutorial.
I did that and works but just with buddylist, it still appearing the username in navigate block and on the title of BuddyList
How can i make that in all drupal override the username with real name ?

Thanks

dosensocial's picture

I follow the instructions and there is a problem in administrator section, if you go to users
Drupal not shows the username …
What happen with that ?

DrupalSN's picture
Hi, You are overriding the function theme_username() which is used throughout Drupal including the admin pages, so any changes you make to the function will be reflected throughout your Drupal site!

As for showing the users real name, you'd need to setup the profile module with a user "real name" field and make it a required field on your registration page. Then at the top of the theme_username function change the $object->name variable:

<?php
function phptemplate_username($object) {
 
$object->name = $object->profile_real_name;
 
  if (
$object->uid && $object->name) {.........
?>
That assumes you have a profile field called "Real Name".

A useful debug you can use to see what variables you have available to you in $object is:
<?php
print_r
($object);
?>
Which will print onscreen all the available variables so you can see what you have to work with.

Hope that helps Tom

This gives me WSOD – I’m on Drupal 5.x is it for Drupal 6.x?

From chaos order also as in the shallow depth. Goodness me why dont? Fantastic job! FYI how about Benghazi wonderful news flash what does one reckon Thanks Flash Web Sites korjausrakentaminen

I think it is important to know the theme function: A theme function is a PHP function withing Drupal that is prefixed with theme_. Theme functions display HTML, and which can be customized by themes.
fatburningfurnace

getbrowser's picture

Could you tell me how to build a site with Drupal?
I am still not familiar with the process of it because of lack of relevant knowledge. What’s a pity!

___________________
Duia – Online Business Guide

There are tons of good drupal video tuts
mainly: gotdrupal.com and mustardseedmedia.com
however if you need personal help, go to q&a page of this site
or you can also contact me
i’ll try to help everyone as good as i can

You definitely did a great job on this! Thank you for putting so much effort on this post and for sharing your knowledge! Keep up the good work!

Thanks & Regards,
Eiffel tower tours

The combination of marketing and graphic design expertise in our team has been very successful. Our Drupal themes are beautiful, and have a clear purpose and goals. Thanks.
Regards,
Box Trailer

Thanks for posting this. I had been looking for the answer until I stumpled upon this.

MZ
online fortune teller

We are the famous laptop adapter manufacturer, laptop adapter factory, and laptop adapter supplier in china. We sell all kinds of different wholesale laptop adapter. You will be satisfied with our china laptop adapter.

REally good post, has helped me out a lot and I have learned something new so thanks.

canvas prints

This is such a great resource that you are providing and you give it away for free. I love seeing websites that understand the value of providing a quality resource for free.

casino en ligne

i think it s a little bit difficult…
Which will print onscreen all the available variables so you can see what you have to work with?
Torrents

Great! I solve my problem… You shot direct to the point. Thanks.

Book gestante BH

This is good for me, as I am new in learning Drupal. This will help me a lot.
ipad case

thanks you very good – nice site
شات الحبشات بنات مصردردشة مصريةدردشة الحب

very nice
thanks

It is a great articles. it gives me a lot of information. before reading this article, I do not know about it. but now, after reading your article, I get it. Thank you..

tinnitus treatment

This was a really well done guide. I’ve been looking through articles on this all morning and found nothing important however this
was of better quality. Thank you.
harry potter |

movie torrents

The main idea of online shopping is not just in having a good looking website that could be listed in a lot of search engines or the art behind the site. It also is not only just about disseminating information, because it is also about building relationships and making money. Mostly, scjp braindumps / scwcd braindumps / scbcd braindumps / scmad braindumps / VCP-410 dumps / 350-001 dumps / 640-802 dumps / SY0-301 dumps organizations try to adopt techniques of online shopping without understanding these techniques and/or without a sound business model. Rather than supporting the organization’s culture and brand name, the website should satisfy consumer’s expectations.

The main idea of online shopping is not just in having a good looking website that could be listed in a lot of search engines or the art behind the site. It also is not only just about disseminating information, because it is also about building relationships and making money. Mostly, scjp braindumps / scwcd braindumps / scbcd braindumps / scmad braindumps / VCP-410 dumps / 350-001 dumps / 640-802 dumps / SY0-301 dumps organizations try to adopt techniques of online shopping without understanding these techniques and/or without a sound business model. Rather than supporting the organization’s culture and brand name, the website should satisfy consumer’s expectations.

The main idea of online shopping is not just in having a good looking website that could be listed in a lot of search engines or the art behind the site. It also is not only just about disseminating information, because it is also about building relationships and making money. Mostly, scjp braindumps / scwcd braindumps / scbcd braindumps / scmad braindumps / VCP-410 dumps / 350-001 dumps / 640-802 dumps / SY0-301 dumps organizations try to adopt techniques of online shopping without understanding these techniques and/or without a sound business model. Rather than supporting the organization’s culture and brand name, the website should satisfy consumer’s expectations.

lmjfengying36's picture

La vendita MBT MBT Scarpe Prezzi scarpe calde questo MBT Scarpe Opinioni giorni! Hanno la MBT Scarpe Outlet reputazione di “più MBT Tembea Black piccola palestra del MBT Chapa mondo”). Masai Barefoot MBT Kisumu Technology inventato dall’ingegnere MBT Walking svizzero Karl Muller, Uomo MBT Sport in una visita in MBT Tataga Corea, ha trovato Uomo MBT Tembea camminare a piedi MBT Karani nudi nelle risaie MBT Anti alleviato il suo dolore lmjafengying36 alla schiena.

lmjfengying36's picture

Jeg som sagt tidligere GHD Rettetang Salg har skikkelig afrohår Ghd Straighteners. Jeg har egentlig Ghd Hair Straighteners masse krøller og Ghd Styler retter ut håret Ghd Purple Indulgence mitt hver eneste Ghd Purple Straighteners dag. Verste er at, Ghd Leopard jeg har egentlig Ghd Dark Iv Styler ikke krøller engang, GHD Diamond Straighteners jeg har bare..Ghd Salon Styler Jeg har rettet Ghd Precious Straighteners ut håret hver Ghd Blue Serenity dag siden 9.klasse Ghd Gold Styler ca, og jeg har lmjafengying36 aldri klart å investere i en god rettetang.

This is a very informative article.I was looking for these things and here I found it. I am doing a project and this information is very useful me.
Estudiar ingles en el extranjero

I have found your blog long ago and continue reading it up-to-date! But now I have decided to register and write a comment for those who are here for the first time! Do not pass by!! Do not look at the site design! The content is surely what you need from this topic! Stay with us and enjoy!
children quotes

Very nice one article thnx for such type of articles i realy enjoy it to read..
instant unsecured bad credit loans
unsecured loans instant approval

unsecured loans instant decision
unsecured laons for people with bad credit
Get all loans in uk with us

Im Gegensatz zu bekannten Marken, was ist das gleich beim ersten sehr beliebt ihrer Mäntel, moncler am Anfang Produkte moncler umfasst Moncler Daunenjacke für diejenigen unter Ihnen. Im Falle der großen Vielfalt von moncler spencer, diskutiert moncler übermäßig auf Moncler zum Kauf Effizienz angeht und setzen Ruhestätte gegenüber nicht mehr!. Moncler nutzen Puffy Jacke, die mit der Innenseite, Schritt zu halten Ihr System zu stellen moncler Topper in die altmodische Art und unterstützt wird. Von Ihrer eigenen Außenseite haben wild und gemütlich Einsparungen wurden von Plopp in der Verantwortung des genäht genommen. Die Ergebnisse Nähte Berater Kurzmantel liegt sicherlich in Ordnung, jede Art von Verletzung im Falle des Tragens von ihnen etwa zu vermeiden. Verbringen Sie einige Art auf moncler Oberbekleidung für die Kleinen Europea Inhaber Moncler Jacken Damen Sommermonaten Zeit beliebt für Ihre glänzenden Schnee und Aufrechterhaltung wehende Wind, Moncler Daunenjacken, nicht seine oder Mäntel nicht scheinen, um typische Mäntel werden. Der Zweck von zu Hause schmücken moncler Oberbekleidung ständig andere Unternehmen weg von mild Ort, um starke Kopfschmerzen kalt. Sie nutzen sehr kalt manchmal Spektrum an Knöchel, wird Urlauber wohl kleide dich in eine andere Oberbekleidung in ihrer normalen Moncler Spezialist erzeugen nur intensive crushed ice ständig, die verliert. Jedesmal, Moncler Online wenn man tatsächlich Kunststoffen Ladengeschäft, eine Gruppe von Menschen genießen alle Entwürfe für moncler Teile. Erhältlich Jacken globalen, dass jeder dieser Ansatz Optik genau das gleiche. Mai auch seine Weste Befreiung, Programmierer, die wurden moncler Taschen machen eine Investition Sanierung auf Design und Farben. Nach dem Bau Rampenlicht Farbkombination sculpted Wechselwirkungen ist es schwer zu glauben, weiß und halten weiß gefärbte moncler Taschen national.

Theatricals, moncler outlet, la caccia, e Dio sa che altro! Ma non parliamo di me, dimmi come hai fatto tutto. Spesso mi chiedo a voi, Annette-how alla tua età si può correre da solo in una carrozza a Mosca, a Pietroburgo, piumini moncler, ai ministri e grandi persone, e sanno come trattare con tutti! E ‘abbastanza sorprendente. Come sei arrivato salert cose: d? Non potrei farlo. “” Ah, giubbotti moncler, amore mio “, rispose Anna Mikhaylovna,” mai Dio vi conceda di sapere cosa vuol dire essere rimasta vedova senza mezzi e con un figlio ti amo alla follia! Si impara molte cose allora “, ha aggiunto con un certo orgoglio.” Questo processo mi ha insegnato molto. Quando voglio vedere una di quelle persone grandi scrivo una nota: ‘principessa tal dei desideri Quindi un’intervista Così e così,’ e poi prendere un taxi e andare io stesso due, tre o quattro volte, fino a Ottengo quello che voglio. . Non mi importa quello che pensano di me “” Beh, e per chi hai applicare circa Bory “chiese la contessa” Vedete è tuo avviso:. Dy un ufficiale della Guardia, mentre il mio Nicholas sta andando come un cadetto. Non c‘è nessuno a cui interessarsi per lui. A chi si applica? “” Per il principe Vasili. Era così gentile. Ha subito accettato di tutto, e mettere il malert: prima l’imperatore “. Disse la Principessa Anna Mikhaylovna con entusiasmo, dimenticando tutte le umiliazioni che aveva subito per guadagnare la sua fine” ha Principe Vasili età molto “chiese la contessa.” Ho non l’ho visto da quando abbiamo agito insieme alla teatralità del Rumyantsovs ‘. Mi aspetto che lui mi ha dimenticato. Egli avviso: ed articoli

Thanks for this information

Comunicação Visual

moncler Steckdose ist vor allem eine bekannte Akklimatisierung von schroffen Avantgarde durch über jede klangliche guidelines.Old Navy neben Größe Mäntel und Jacken, Moncler jacket auch Abwechslung in etwa 22 für jede Schlankheitskur blazer Kosten, können 49 zu einer fullLength Wollmischung coat.If müssen Sie durchsuchen guten noch mehr bekommen oft als nicht hinzufügen zu wenige Anzüge frei. Famousbrand Anzug des Ortes Detail wirklich sehr akribisch,. Moncler Steckdose zum Beispiel Rotatorenmanschette Stelle getan, weil sich conterminous sollte analyzed.Several Tagen erreichen, wenn ich einkaufen ging für den nahenden Winter fand ich eine aktualisierte Mode moncler. Moncler Outdoor-Jacken ausdrückliche ein Gefühl in Bezug auf Befehl beliebte Geschäft. Um wettbewerbsfähig fr.moncler outletom bleiben die Wintermonate Moncler 2011 Markt für Bekleidung, muss das Kleid als eye candy angesehen werden und unter Verwendung von nur Ressourcen in die feinsten werden. Moncler Outdoor-Jacken passen, dass die Kosten, während sie um sich wohl zu sein, sehr robust und wasserdicht neigen. Egal, es gibt nichts falsch gehen, um moncler Produkte erwerben, die speziell aus dem world wide web, liefert c.moncler outletomfort und ratewhich bedeutet, dass Sie sich aural ein Akklimatisierung an Ski-Einsatz der Wohlstand und Reichtum von Einsen Moncler outletFor eine Weile dort zu akzeptieren, wenn Sie Googled mein wirkliches Leben Namen konnte man sehen, diese Dinge, die ich sagte, ich wollte Moncler daunenjacken Reporter zitiert hadnt so verdammt genau. Ich habe gelernt, den Reportern sagen, dass alles, was ich sagte, dass sie wer.moncler doudoune hommee zu zitieren werde, sie von mir in Druck bekommen vor der Veröffentlichung, oder ich würde nicht reden mit ihnen zu reden OKed hatte. Zum größten Teil war dies well.Buying Wintermäntel kann eine wunderbare Strategie, bleiben während der wi lanoh Burberry mellow werden.

great theme. I merely came across your site and wished to say that I have really loved reading through your blog posts. Any ways I’ll be subscribing for your feed and I hope you post again soon. Can you suggest any them for my site cute hamsters

This is one of the most informative information I’ve read. It really helps a lot. Thanks for sharing this and teaching some of your Idea’s
granite rockville md

Le Nike Lebron 9 “Tn requin “ dispose d’une prédominance noire supérieure, un swoosh en or avec des accents assortis, lacets et la doublure dynamique qui rappelle les couleurs utilisées dans l‘œuvre d’art créée par le célèbre WTT concepteur de Riccardo Tisci . Le reste de chaussures sur une semelle de propreté bleue et disposent d’un bijou hors massifs à pointes qui se trouve juste en dessous de la langue au centre de la chaussure. Cette sneaker somptueux possède la plus grande bravoure et est clairement digne de ce moniker.Lebron WTT peut-être pas dessiner un salaire de la NBA en ce moment
, Air Max 90 vous êtes toujours d‘être payé par quelqu’un . Commencez à économiser . Si cette chaussure ne vois un communiqué stateside , faites-moi confiance , vous allez avoir une paire . Regardez plus s’occupe de la dernière édition de cette chaussure jump.The superbe seront certainement couronnés les meilleurs du peloton. Le Lebron 9 “ Watch The Throne “ chaussure sera pour le monde baskets ce que le montre l’album Trône est à la communauté hip-hop , du luxe à son meilleur. La tournée WTT a fait une escale à Miami ce soir, il n’y avait donc Tn Nike de meilleur moment pour le roi de dévoiler son dernier -déposer.

Hey thanks i really need to learn this topic & i want to customized my site with drupal. is it possible? my site is based on appointment scheduler.