Display Recently Registered Users in WordPress Sidebar
Sometimes you may want to display a list of recently registered users in your WordPress sidebar or other widget areas. This can be achieved by creating a custom function and shortcode. Below is an optimized and secure code example.
Create the Function to Get Recent Users
Add the following code to your theme's functions.php file or via a code snippets plugin.
/**
* Get recently registered users
*
* @param int $limit Number of users to display (default 5).
* @return string HTML list with avatars and names.
*/
function wp_get_recently_registered_users( $limit = 5 ) {
global $wpdb;
$limit = absint( $limit );
if ( $limit <= 0 ) $limit = 5;
$query = $wpdb->prepare(
"SELECT user_nicename, user_url, user_email FROM {$wpdb->users} ORDER BY ID DESC LIMIT %d",
$limit
);
$users = $wpdb->get_results( $query );
if ( empty( $users ) ) return '';
$output = '';
foreach ( $users as $user ) {
$avatar = get_avatar( $user->user_email, 45 );
if ( ! empty( $user->user_url ) ) {
$profile_url = esc_url( $user->user_url );
$output .= sprintf(
'- %s%s
',
$avatar,
$profile_url,
esc_html( $user->user_nicename )
);
} else {
$output .= sprintf(
'- %s%s
',
$avatar,
esc_html( $user->user_nicename )
);
}
}
$output .= '
';
return $output;
}
/**
* Register shortcode [recent_users]
*/
function wp_register_recent_users_shortcode( $atts ) {
$atts = shortcode_atts( array( 'limit' => 5 ), $atts, 'recent_users' );
return wp_get_recently_registered_users( $atts['limit'] );
}
add_shortcode( 'recent_users', 'wp_register_recent_users_shortcode' );
Key Improvements
- Security: Uses
$wpdb->prepare()for SQL queries and escapes output withesc_url()andesc_html(). - Robustness: Validates the
$limitparameter withabsint(). - Maintainability: Clear function names and documentation.
- Flexibility: Shortcode accepts a
limitattribute.
How to Use
1. Using the Shortcode
Insert in posts, pages, or text widgets:
[recent_users]
Or with custom limit:
[recent_users limit="8"]
2. Direct Function Call in Templates
In theme files like sidebar.php:
<?php echo wp_get_recently_registered_users( 5 ); ?>
Custom Styling
Add CSS to your theme's style.css:
.recently-registered-users {
list-style: none;
padding-left: 0;
}
.recently-registered-users li {
display: flex;
align-items: center;
margin-bottom: 10px;
}
.recently-registered-users .avatar {
border-radius: 50%;
margin-right: 10px;
}
Now you can safely display recently registered users anywhere on your WordPress site.