Displaying Nodeprofile Fields for a User within a Node

I was banging my head against the wall this weekend trying to remember how to display nodeprofile fields with user information. It's actually really easy and I thought I should write a post about how to do it for the next time I forget.

In this case, I have a content type called 'myuserprofile' that is selected as the content type to use for nodeprofiles. In my myuserprofile content type, I have a field for users to enter their favorite food.

There are two easy ways of displaying this information. First, we can grab and display it within a node. For example, say that I want to display a user's favorite food on a page if that user is logged in. To do so, the following would work:

  1. <?php
  2. global $user;
  3. //checking if a user is logged in
  4. if ($user->uid):
  5. //load the nodeprofile user profile for the currently logged-in user
  6. $profile = node_load(array('type'=>'myuserprofile', 'uid'=>$user->uid));
  7. //print out the user's favorite food
  8. print $profile->field_favorite_food[0]['value'];
  9. ?>

A second approach to displaying this information, is to put the following in the _phptemplate_variables function of template.php.

  1. <?php
  2. function _phptemplate_variables($hook, $vars = array()) {
  3. switch ($hook) {
  4. case 'node':
  5. //checking if a user is logged in
  6. if ($user->uid):
  7.  
  8. $vars['profile'] = node_load(array('type'=>'myuserprofile', 'uid'=>$user->uid));
  9. $vars['favorite_food'] = $vars['profile']->field_favorite_food[0]['value'];
  10. endif;
  11. break;
  12. }
  13. return $vars;
  14. }
  15. ?>

Then, I can display the favorite food information on a page with:

  1. <?php
  2. global $user;
  3. print $favorite_food;
  4. ?>

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: <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>. Beside the tag style "<foo>" it is also possible to use "[foo]". PHP source code can also be enclosed in <?php ... ?> or <% ... %>.
  • You can use Markdown syntax to format and style the text. Also see Markdown Extra for tables, footnotes, and more.

More information about formatting options