首先要做的是创建所需的短代码:
function wpusers_shortcode( $atts ) {
// Attributes
$atts = shortcode_atts(
array(
\'group\' => \'logistics\',
),
$atts
);
// code here
}
add_shortcode( \'wpusers\', \'wpusers_shortcode\' );
现在您有了一个自动关闭的短代码。现在是时候查阅数据库以获取所有注册用户了:
$args = array(
\'role\' => \'Subscriber\',
\'order\' => \'ASC\',
\'orderby\' => \'id\',
\'fields\' => \'all_with_meta\',
);
// The User Query
$users = new WP_User_Query( $args );
// The User Loop
if ( ! empty( $users->results ) ) {
foreach ( $users->results as $user ) {
// do something
}
} else {
// no users found
}
使用此代码,您可以获得所有已注册的“Subscriber”类型的用户。您可以通过以下方式更改用户(角色)的类型:“超级管理员”、“管理员”、“编辑”、“作者”、“贡献者”、“订阅者”,甚至您自己的自定义角色:“教师”。
假设您使用的是Bootstrap,以下结构足以生成列:
<div class="container">
<div class="row users">
<div class="col-xs-12 col-sm-4 col-md-3 user">
<div class="user-photo">
<img src="..." width="" height="" />
</div>
<div class="user-info">
<h6>User name</h6>
<p>User job</p>
</div>
</div>
</div>
</div>
如果我们把所有的东西都放在一起,它会是这样的:
function wpusers_shortcode( $atts ) {
// Attributes
$atts = shortcode_atts(
array(
\'group\' => \'logistics\',
),
$atts
);
$args = array(
\'role\' => \'Subscriber\',
\'order\' => \'ASC\',
\'orderby\' => \'id\',
\'meta_query\' => array(
\'relation\' => \'AND\',
array(
\'key\' => \'group\', // custom field here
\'value\' => $atts["group"],
\'compare\' => \'=\',
\'type\' => \'CHAR\',
),
),
\'fields\' => \'all_with_meta\',
);
// The User Query
$users = new WP_User_Query( $args );
ob_start(); // Start buffer ?>
<div class="container"> <?php
if ( ! empty( $users->results ) ) { ?>
<div class="row users"> <?php
foreach ( $users->results as $user ) {
$user_photo = ...;
$user_name = ...;
$user_job = ...; ?>
<div class="col-xs-12 col-sm-4 col-md-3 user">
<div class="user-photo">
<img src="<?= $user_photo["url"] ?>" width="<?= $user_photo["width"] ?>" height="<?= $user_photo["height"] ?>" />
</div>
<div class="user-info">
<h6><?= $user_name ?></h6>
<p><?= $user_job ?></p>
</div>
</div> <?php
} ?>
</div> <?php
} else { ?>
<div class="row user-no-result">
<div class="col">
<div class="alert alert-warning">
<p><?= __("No users found.", "theme") ?></p>
<a class="btn btn-link"><?= __("Return to home", "theme") ?></a>
</div>
</div>
</div> <?php
} ?>
</div> <?php
$output = ob_get_contents(); // Get buffer content
ob_end_clean(); // Clear buffer
return $output; // Return generated html
}
add_shortcode( \'wpusers\', \'wpusers_shortcode\' );
希望你帮忙,问候!