WordPress allows us to add any kind of content to any section of its backend. In this post I'll show you how to add custom fields and data to the profile page of WordPress users.
Imagine that your web site extends the base WordPress user profile and stores additional data related to each user. For example, you could decide to show a download history for each user.
Here's how you can show such an history on the user's profile. Add the following to your functions.php
file:
if(current_user_can('subscriber')) {
add_action( 'show_user_profile', 'user_download_history' );
}
function user_download_history() {
global $wpdb;
$table = 'user_downloads';
global $current_user;
get_currentuserinfo();
$id = $current_user->ID;
$results = $wpdb->get_results("SELECT wp_user, filename, fileurl FROM $table WHERE wp_user = $id");
$html = '<h3>Your downloads</h3>';
$html .= '<table class="form-table">';
foreach($results as $result) {
$html .= '<tr>';
$html .= '<th>' . str_replace('.pdf', '', $download->filename) . '</th>';
$html .= '<td><a href="' . $download->fileurl . '">Download</a></td>';
$html .= '</tr>';
}
$html .= '</table>';
echo $html;
}
Now subscribers can view their download history. So far so good. Now imagine that you want to allow administrators to view the download history of each user. Here's how you can do:
if(current_user_can('administrator')) {
add_action('edit_user_profile', 'admin_user_download_history');
}
function admin_user_download_history() {
global $wpdb;
$table = 'user_downloads';
$id = intval($_GET['user_id']);
$results = $wpdb->get_results("SELECT wp_user, filename, fileurl FROM $table WHERE wp_user = $id");
$html = '<h3>User downloads</h3>';
$html .= '<table class="form-table">';
foreach($results as $result) {
$html .= '<tr>';
$html .= '<th>' . str_replace('.pdf', '', $download->filename) . '</th>';
$html .= '<td><a href="' . $download->fileurl . '">Download</a></td>';
$html .= '</tr>';
}
$html .= '</table>';
echo $html;
}
In this case we've used the GET variable user_id
which is set on every user profile that needs to be edited. Very handy.