In order to build an Author Page, Author Box we need to pull out Author’s Meta Data such as First Name, Last Name, Bio, Phone Number (Custom Field…). There are some ways to do this:

1/ Get User Meta Data via $curauth

Use this code snippet in author.php (Author template file) to get author’s meta data

<?php 
$curauth = (isset($_GET['author_name'])) ? get_user_by('slug', $author_name) : get_userdata(intval($author));
?>

Now that you have the $curauth variable set up, you can use it to display all kinds of information about the author whose page is being displayed. For example, to display the author’s nickname, in a format like “This is Joe’s page”, you could use:

<p>This is <?php echo $curauth->nickname; ?>'s page</p>

There are many other pieces of information you can display, besides the author’s nickname. All of these come from the WordPress user editing screen:

  • $curauth->description;
  • $curauth->display_name;
  • $curauth->first_name;
  • $curauth->ID;
  • $curauth->last_name;
  • $curauth->nickname;
  • $curauth->user_email;
  • $curauth->user_login;
  • $curauth->user_nicename;
  • $curauth->user_registered;
  • $curauth->user_url;

If you add a user’s custom field, use can get that field’s value with this code:

$curauth->your_custom_field;

2/ Get User Meta Data via UserID

Use this code snippet to get User Meta Data via ID

?php 
  $user_id = 9;
  $key = 'last_name';
  $single = true;
  $user_last = get_user_meta( $user_id, $key, $single ); 
  echo '<p>The '. $key . ' value for user id ' . $user_id . ' is: ' . $user_last . '</p>'; 
?>

In order to retrieve all meta data for the given user (in this example, user_id = 9), use this code snippet

<?php
  $all_meta_for_user = get_user_meta( 9 );
  print_r( $all_meta_for_user );
?>

Result after print

Array ( [first_name] => Array ( [0] => Tom ) [last_name] => Array ( [0] => Auger) [nickname] => Array ( [0] => tomauger ) [description] => etc.... )

In order to access the data in this example, you need to access the array that is returned for each key, like so:

$description= $all_meta_for_user['description'][0];//Get Bio's decription

To learn more about this method, check Getting All Meta Data at WordPress Codex.

Credit:

GiangLe.DEV

My name is Giang, a Vietnamese guy living in Thanh Hoa City, Vietnam. I am a WordPress Developer, learning to master WordPress and Laravel PHP Framework.

Leave a Reply

avatar
  Subscribe  
Notify of
Close Menu