Adding A Class To A Drupal Theme For Logged In Users

I was working on a Drupal theme recently which required a number of different elements to be present on a number of different pages, but only for logged in users.

Using a little PHP I was able to add a class of 'in' to the body which would only appear in the html when a user was logged in.

To do this, just find the opening <body> tag in your page.tpl.php file, and add in the code below.

<body<?php global $user; ?><?php if ($user->uid): ?> class="in"<?php endif; ?>>

Then, you'll be able to write a general rule for logged out users, such as:

body {
background: #fff;
}

And a more specific rule for logged in users, such as:

body.in {
background: #000;
}

7 comments

1
Jan HeynenOctober 27th 2007 @ 02:07PM

How simple can things be?
Great post!

Jan

2
GuestOctober 29th 2007 @ 08:07PM

Pretty cool. Anyone have any examples where this would be useful? I know that the Zen theme comes with this as well.

3
BrianNovember 14th 2007 @ 04:33PM

This seems like a slick and simple solution, but isn't there a potential security risk to making the $user variable global? I've seen this example in several other places, but no one has addressed the security angle.

4
MichaelGuestMay 25th 2008 @ 06:21PM

do you know what i would need to do to allow loged in users the ability to see a "form" that has been written in html? It's a form that allows the user to log into there email address and right now i have to re direct the user to another site.

5
LaurenceMay 27th 2008 @ 01:04PM

Hi Michael, where is the form exactly?

6
GuestJuly 14th 2008 @ 02:08PM

gr8 post. Its like cutting a birthday cake

7
inzOctober 26th 2009 @ 04:18PM

This is exactly what i'd like to do. I tried it and it works... sort of.

I'm using the pixture-reloaded theme, the body tag looks like this:
<body id="pixture-reloaded" class="<?php print $body_classes; ?> <?php print $logo ? 'with-logo' : 'no-logo' ; ?>">

I then add the if-statement like this:
<body <?php global $user; ?><?php if ($user->uid): ?> class="in"<?php endif; ?> id="pixture-reloaded" class="<?php print $body_classes; ?> <?php print $logo ? 'with-logo' : 'no-logo' ; ?>">

Now things won't show up the way they should... For example, the content-area shows up behind the left sidebar, and i haven't even added any css for "in" yet.

What am i doing wrong?

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.

More information about formatting options

4 + 9 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.