0

First of all, I am not a techie and have picked the codes mentioned below from various sources. I have added two new fields to the user profile - 'firstname' and 'surname'. I am using a custom theme and on one of the places (on a node), I need to display the real name (making some code changes) instead of the username.

I am replacing the existing code -

<h3><?php print $node->name ?></h3>

With this -

<h3><?php 
     $profile = user_load($node->uid); 
     $profile = user_view($profile); 
     $firstname = render($profile['field_firstname']); 
     $surname = render($profile['field_surname']); 
     print $firstname.' '.$surname; ?></h3>

However, a strange thing is happening. I am able to print the surname correctly but the firstname is blank every time, even when I tried to print only the firstname (or the surname). Why is it that the firstname is not getting picked? What changes should I make?

1
  • 1
    Actually you don't have to load it using $profile = user_view($profile); since profile fields are already loaded in $user object. Please refer my answer below.
    – Ram
    Commented Aug 1, 2013 at 5:12

2 Answers 2

1

You can load the node object from the nid and from the node you can get user object.

With user object we can able to get firstname and lastname field values, if there is one. usually a node submitted by anonymous user will have no name.

you can try this code.This works in drupal7.

<?php 
    $node = node_load($nid);    
    $profile = user_load($node->uid);      
    $firstname = $profile->field_first_name['und'][0]['value'];
    $surname = $profile->field_last_name['und'][0]['value'];
    print $firstname.' '.$surname;
?> 
0
2

Did you try real name module before write your own code?

I did not use 6.x version, but i guess it will be more flexible than your solution.

3
  • OP should be using D7 (render() isn't available in d6)
    – AKS
    Commented Jul 31, 2013 at 23:19
  • I've never seen name property of node object in D7. Anyway realname module available for both 6 and 7 versions. Commented Jul 31, 2013 at 23:29
  • Thanks. I am already using realname but somehow, the real name is being displayed at every place in the site except for one. I am assuming that I will have to change it manually there by making some code changes and so I tried doing this.
    – user18593
    Commented Aug 1, 2013 at 10:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.