WordPress 隨機顯示已註冊的用戶

之前我們分享過 WordPress 顯示最近註冊的用戶,今天再來實現 隨機顯示已註冊的用戶。方法其實都幾乎一樣,僅僅是查詢數據庫的代碼有點差異罷瞭。

將下面的代碼添加到當前主題的 functions.php:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
 * WordPress 隨機顯示已註冊的用戶
 * https://www.wpdaxue.com/display-random-registered-users.html
 */
function wpb_random_users() { 
	global $wpdb;
	$randomusers = '<ul class="random-users">';
	// 查詢數據庫,隨機獲取 5 位已註冊用戶
	$usernames = $wpdb->get_results("SELECT user_nicename, user_url, user_email FROM $wpdb->users ORDER BY RAND() LIMIT 5");
	// 將用戶已列表的形式顯示
	foreach ($usernames as $username) {
		if (!$username->user_url) :
			$randomusers .= '<li>' .get_avatar($username->user_email, 45) .$username->user_nicename."</li>";
		else :
			$randomusers .= '<li>' .get_avatar($username->user_email, 45).'<a href="'.$username->user_url.'">'.$username->user_nicename."</a></li>";
		endif;
	}
	$randomusers .= '</ul>';
	return $randomusers;  
}
// 添加簡碼
add_shortcode('randomusers','wpb_random_users');

/**
* WordPress 隨機顯示已註冊的用戶
* https://www.wpdaxue.com/display-random-registered-users.html
*/
function wpb_random_users() {
global $wpdb;
$randomusers = ‘<ul class="random-users">’;
// 查詢數據庫,隨機獲取 5 位已註冊用戶
$usernames = $wpdb->get_results("SELECT user_nicename, user_url, user_email FROM $wpdb->users ORDER BY RAND() LIMIT 5");
// 將用戶已列表的形式顯示
foreach ($usernames as $username) {
if (!$username->user_url) :
$randomusers .= ‘<li>’ .get_avatar($username->user_email, 45) .$username->user_nicename."</li>";
else :
$randomusers .= ‘<li>’ .get_avatar($username->user_email, 45).'<a href="’.$username->user_url.’">’.$username->user_nicename."</a></li>";
endif;
}
$randomusers .= ‘</ul>’;
return $randomusers;
}
// 添加簡碼
add_shortcode(‘randomusers’,’wpb_random_users’);

然後你就可以在樣版中使用下面 的函數調用

1
<?php wpb_random_users(); ?>

<?php wpb_random_users(); ?>

或者在文章、頁面或小工具中使用下面的簡碼調用

[randomusers]

參考資料:http://www.wpbeginner.com/wp-tutorials/how-to-randomly-display-registered-users-in-wordpress/

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *