I'm building my first site with drupal. And I made a custom user field: Full name. Now I want to get the value of this fild in my template to say “Hello, %username%”. How do I do that?
Clive's answer is correct except that you should use field_get_items
to get the values for a field. It will handle the language for you. You should also sanitize the value.
function THEME_preprocess_page() {
global $user;
$user = user_load($user->uid); // Make sure the user object is fully loaded
$full_names = field_get_items('user', $user, 'field_full_name');
if ($full_names) {
$vars['full_name'] = check_plain($full_names[0]['value']);
}
}
If your site uses the Entity API module, you can also use a entity metadata wrapper like this
function THEME_preprocess_page() {
global $user;
$user = user_load($user->uid); // Make sure the user object is fully loaded
$wrapper = entity_metadata_wrapper('user', $user);
$vars['full_name'] = $wrapper->field_full_name->get(0)->value(array('sanitize' => TRUE));
}
See also Writing robust code that uses fields, in Drupal 7
Depending on your setup/field name, something like this in template.php
(preprocess function for the template file):
function mytheme_preprocess_page() {
global $user;
$user = user_load($user->uid); // Make sure the user object is fully loaded
$vars['full_name'] = $user->field_full_name[LANGUAGE_NONE][0]['value'];
}
Then something like this in page.tpl.php
:
if (isset($full_name) && !empty($full_name)) :
echo 'Hello ' . $full_name;
endif;
Note that LANGUAGE_NONE
may need to be changed if you're running a multi-lingual site.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With