Handy code snippet to display all wp_usermeta associated with a user's profile.
- This snippet is locked to only display meta for site admins
- The meta is shown at the bottom of the user's profile page in the backend.
- The data is non editable.
- This is a WordPress code snippet.
<?php
/**
* Display all user meta fields on the user profile page for admins only, showing meta for the viewed user.
*/
function display_target_user_meta_for_admins( $profile_user ) {
// Check if the current user is an admin.
if ( current_user_can( 'administrator' ) ) {
// $profile_user is an object containing the user data for the profile being viewed.
$user_id = $profile_user->ID;
// Retrieve all user meta for the viewed user.
$user_meta = get_user_meta( $user_id );
// Output the meta data.
echo '<div class="user-meta-display">';
echo '<h3>User Meta Data for ' . esc_html( $profile_user->display_name ) . '</h3>';
echo '<table class="wp-list-table widefat fixed striped">';
echo '<thead>';
echo '<tr>';
echo '<th>Key</th>';
echo '<th>Value</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
if ( ! empty( $user_meta ) ) {
foreach ( $user_meta as $key => $values ) {
echo '<tr>';
echo '<td>' . esc_html( $key ) . '</td>';
echo '<td>';
if ( is_array( $values ) && count( $values ) > 1 ) {
echo '<ol>';
foreach ( $values as $value ) {
echo '<li>' . esc_html( maybe_serialize( $value ) ) . '</li>';
}
echo '</ol>';
} elseif ( is_array( $values ) && count( $values ) == 1 ) {
echo esc_html( maybe_serialize( $values[0] ) );
} else {
echo esc_html( maybe_serialize( $values ) );
}
echo '</td>';
echo '</tr>';
}
} else {
echo '<tr><td colspan="2">No user meta found for this user.</td></tr>';
}
echo '</tbody>';
echo '</table>';
echo '</div>';
}
}
// Hook the function to the user profile page.
// The 'show_user_profile' and 'edit_user_profile' actions pass the user object to the callback function.
add_action( 'show_user_profile', 'display_target_user_meta_for_admins' );
add_action( 'edit_user_profile', 'display_target_user_meta_for_admins' );How to Use
- Access your WordPress site's
functions.phpfile (usually located inwp-content/themes/your-theme-name/). - Paste the updated code snippet at the end of the file.
- Save the
functions.phpfile. - Navigate to the 'Users' section in your WordPress admin area, and click on 'All Users'. Then, click 'Edit' for any user. As an administrator, you will now see a table at the bottom displaying all
wp_usermetafields associated with that specific user.
Important Considerations
- Security: Be mindful of the data you're displaying. User meta can contain sensitive information.
- Performance: Displaying a large amount of user meta data can potentially impact performance. Consider optimizing the code if you have a very large number of meta fields.
- Customization: You can customize the output further by modifying the HTML structure or adding CSS styles to match your theme's design.