If you take a look at node.tpl.php
, you'll notice there's already a variable for this type of data: $submitted
. You could replace that variable with your own data, but to do it the Drupal way, what you want to do is modify the value of $submitted
using a preprocess function.
In your theme, create a template.php
file (if you don't have one already). In it, add the following function (replacing example
with the short name of your theme):
function example_preprocess_node(&$variables) {
// Linkify the URL
$twitter_url = l('http://twitter.com/someusername', 'http://twitter.com/someusername');
// This is the same thing as saying
// $variables['submitted'] = $variables['submitted'] . ' ' . $twitter_url;
$variables['submitted'] .= ' ' . $twitter_url;
}
Clear the cache (Configuration → Performance → Clear cache), and check your node pages again: you should see the Twitter URL appended to submitted line.
But this is of course, static: to load the user's Twitter URL, you'll need to load the field data:
function example_preprocess_node(&$variables) {
// Even though there's a user object in $variables['user'], we need to
// load a new copy because the preloaded one doesn't have have field data
$user = user_load($variables['uid']);
// Retrieve the data and its value for the Twitter URL field
// Replace field_twitter_url with the short name of the field
// found at admin/config/people/accounts/fields
$items = field_get_items('user', $user, 'field_twitter_url');
$field = field_view_value('user', $user, 'field_twitter_url', $items[0]);
// Get the rendered output of the field for use in the submitted line
$twitter_url = drupal_render($field));
// If you wanted to get more fields, repeat the last three lines, replacing
// field_twitter_url with the names of the other fields.
// Linkify the URL and append it to the $submitted variable
$variables['submitted'] .= ' ' . l($twitter_url, $twitter_url);
}
The Field API isn't the most intuitive or straightforward API in the world, but here's what's going on:
- Load the user object, which contains the information about the fields attached to it.
- Load the specific data associated with the
field_twitter_url
using field_get_items()
.
- Get the render array for the specific field you want to display using
field_view_value()
.
- Get the final rendered output using
drupal_render()
.
Now, if you wanted to have the Twitter URL separate (so you can move it to where ever you want in the template), just create your own variable:
function example_preprocess_node(&$variables) {
// ...
// Do all the stuff from the previous sample function, except
// setting $variables['submitted']
// ...
$variables['twitter_url'] = $twitter_url;
}
Now, you can add $twitter_url
to anywhere in node.tpl.php
. If your theme doesn't already have its own node.tpl.php
, navigate to the modules/node
folder, copy the node.tpl.php
that's there to your theme folder, and clear the cache.