PHP

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;
}

Adding A Permalink

I got the idea for today's post after I received an e-mail during the week from Colin who was wondering how I added a permalink, and then styled the links section so that everything (comments, read more, permalink etc.) lines up.

I thought this might be of general interest, so here's the answer.

It's basically just a two step process:

  • add some markup to the node.tpl.php file
  • add some css to the style.css file

Step 1 - Add markup to the node.tpl.php file

To start with I just added some markup to the links div, and then positioned the whole links div at the end of my node.tpl.php file, right before the closing node div tag.

   <?php if ($links): ?>
   <div class="links">
      <p class="permalink"><a href="<?php print $node_url ?>" title="Permalink to this my Drupal blog post">Permalink</a></p>
      <?php print $links ?> 
   </div>
   <?php endif; ?>

This positioned the permalink within the links div before the other links.