你真的不应该用皮平的答案。查询效率很低。$user_count_query
在本例中,可以将数据库中最多999999个用户以及所有用户字段返回到脚本中。如果/当您的站点足够大时,这肯定会达到PHP的内存和/或时间限制。
但这可能是2012年唯一的解决方案。
这里有一个更好的方法。在这个例子中,我只有next and previous page 但是如果您确实需要编号分页,那么可以使用变量来构建它。据我所知,WordPress没有与WP\\u User\\u Query兼容的分页功能。
<?php
// Pagination vars
$current_page = get_query_var(\'paged\') ? (int) get_query_var(\'paged\') : 1;
$users_per_page = 2; // RAISE THIS AFTER TESTING ;)
$args = array(
\'number\' => $users_per_page, // How many per page
\'paged\' => $current_page // What page to get, starting from 1.
);
$users = new WP_User_Query( $args );
$total_users = $users->get_total(); // How many users we have in total (beyond the current page)
$num_pages = ceil($total_users / $users_per_page); // How many pages of users we will need
?>
<h3>Page <?php echo $current_page; ?> of <?php echo $num_pages; ?></h3>
<p>Displaying <?php echo $users_per_page; ?> of <?php echo $total_users; ?> users</p>
<table>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<?php
if ( $users->get_results() ) foreach( $users->get_results() as $user ) {
$firstname = $user->first_name;
$lastname = $user->last_name;
$email = $user->user_email;
?>
<tr>
<td><?php echo esc_html($firstname); ?></td>
<td><?php echo esc_html($lastname); ?></td>
<td><?php echo esc_html($email); ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
<p>
<?php
// Previous page
if ( $current_page > 1 ) {
echo \'<a href="\'. add_query_arg(array(\'paged\' => $current_page-1)) .\'">Previous Page</a>\';
}
// Next page
if ( $current_page < $num_pages ) {
echo \'<a href="\'. add_query_arg(array(\'paged\' => $current_page+1)) .\'">Next Page</a>\';
}
?>
</p>
第2页示例:
<2018年6月8日更新:如果您想
page numbers 这里不是下一页/上一页链接,而是如何设置。请注意,您需要将数字替换为页面链接,在本例中它们将不可单击(基于
https://stackoverflow.com/a/11274294/470480, 修改为显示一致数量的中间数字,而不是添加“…”除非实际跳过了页面)。
您还可以看到my gist file 其中包含用于此目的的可重用函数。
$current_page = 5; // Example
$num_pages = 10; // Example
$edge_number_count = 2; // Change this, optional
$start_number = $current_page - $edge_number_count;
$end_number = $current_page + $edge_number_count;
// Minus one so that we don\'t split the start number unnecessarily, eg: "1 ... 2 3" should start as "1 2 3"
if ( ($start_number - 1) < 1 ) {
$start_number = 1;
$end_number = min($num_pages, $start_number + ($edge_number_count*2));
}
// Add one so that we don\'t split the end number unnecessarily, eg: "8 9 ... 10" should stay as "8 9 10"
if ( ($end_number + 1) > $num_pages ) {
$end_number = $num_pages;
$start_number = max(1, $num_pages - ($edge_number_count*2));
}
if ($start_number > 1) echo " 1 ... ";
for($i=$start_number; $i<=$end_number; $i++) {
if ( $i === $current_page ) echo " [{$i}] ";
else echo " {$i} ";
}
if ($end_number < $num_pages) echo " ... {$num_pages} ";
输出(从第1页到第10页):
[1] 2 3 4 5 ... 10
1 [2] 3 4 5 ... 10
1 2 [3] 4 5 ... 10
1 2 3 [4] 5 ... 10
1 ... 3 4 [5] 6 7 ... 10
1 ... 4 5 [6] 7 8 ... 10
1 ... 6 [7] 8 9 10
1 ... 6 7 [8] 9 10
1 ... 6 7 8 [9] 10
1 ... 6 7 8 9 [10]