July 8, 2009

Custom user profile page in Drupal

Filed under: Tips — Tags: , — Webopius @ 5:04 pm

In Drupal, a standard user profile page will say something like:

Member for
30 weeks 2 days

Pretty dull isn’t it?

In this article, I’m going to try to show you how to enhance this page to show the user’s name and their most recent 10 articles. You can take this code as a base and create pretty much any type of user profile page you want.

Override the theme user_profile

Drupal’s theme system is very powerful but also somewhat complex to follow. The idea is that existing modules generate their output using named themes and you can override this output by writing your own theme function or theme template file.

In the case of the user profile, unsurprisingly¬† the theme is called ‘user_profile’ and exists originally in Drupal’s user module (user.pages.inc).

We will be overriding the theme with a theme function in this example. You can choose to either user a function or a template file.

Overriding with a function

As an example, assuming you were using a phptemplate based theme called ‘mytheme’ for your Drupal site, Drupal would look for the following function names in your enabled modules. If it finds a match it will use this function instead of the standard user module’s theme function for rendering the user profile details:


Overriding with a template file

If you choose not to use a function, you can create/edit the file ‘sites/all/themes/custom/mytheme/user_profile.tpl.php’

Custom User profile code

Once you’ve decided where you will be placing the user_profile theme code, this is an example of the code. In my case, I’ve used the example with the function name mytheme_user_profile().

function mytheme_user_profile($account) {
	$output = '<div class="profile">';
	$output.='Hi '.$account->name.'<br />';
        $output .= '</div>';
 	$output .= '<p>Your 10 most recent posts</p>';

 	$uid = $account->uid;
  	$result = db_query_range(db_rewrite_sql("SELECT n.nid, n.title FROM {node} n WHERE n.uid = %d and n.status=1 ORDER BY n.changed DESC"), $uid, 0, 10);

  	$output .= '<ul>' ;
	while ($data = db_fetch_object($result)) {
	  	$output .= '<li>'.l(check_plain($data->title),"node/$data->nid") . ' <a href="'.$edit.'">edit</a></li>';
	$output .= '</ul>';

  return $output;

Now, when a user visits their ‘myaccount’ page, they will see their name at the top followed by a list of their 10 most recent postings. Alongside each posting is a link to edit. You can use this framework to show any user related information you like within this profile.

  • Tags