如何显示WP_User_Query的分页链接?


10

我想我已经差不多了,但是我无法获得分页链接来显示我正在创建的作者目录。

我的代码在下面,但是我不知道如何获取链接以在作者的工作页面之间导航。谁能帮我?我感觉这可能有用,但是我不知道如何实现它:

paginate_links()

谢谢

大须

    <?php 
/* ****************************************************************** */
                        /* !LIST AUTHORS */
/* ****************************************************************** */ 

// THANKS TO:
// http://www.mattvarone.com/wordpress/list-users-with-wp_user_query/

// pagination
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1; // Needed for pagination
$paged -= 1;
$limit = 2;
$offset = $paged * $limit;

// prepare arguments
$args  = array(
    // search only for Authors role
    'role'      => 'Subscriber',
    // order results by display_name
    'orderby'   => 'display_name',
    // return all fields
    'fields'    => 'all_with_meta',
    'number'    => $limit,
    'offset'    => $offset      
);
// Create the WP_User_Query object
$wp_user_query = new WP_User_Query($args);
// Get the results
$authors = $wp_user_query->get_results();
// Check for results
if (!empty($authors))
{
    echo '<div class="author-entry">';
    // loop trough each author
    foreach ($authors as $author)
    {
        $author_info = get_userdata($author->ID); ?>

        <span style="float:left;padding:0 5px 0 0;"><?php echo get_avatar( $author->ID, 50 ); /* http://codex.wordpress.org/Function_Reference/get_avatar */ ?></span>
        <span class="fn"><strong>First name</strong> : <?php echo $author_info->first_name; ?></span><br />
        <span class="ln"><strong>Last name</strong> : <?php echo $author_info->last_name; ?></span><br />
        <span class="em"><strong>Email address</strong> : <a href="mailto:<?php echo $author_info->user_email; ?>"><?php echo $author_info->user_email; ?></a></span><br />
        <span class="we"><strong>Website</strong> : <a href="<?php echo $author_info->user_url; ?>"><?php echo $author_info->user_url; ?></a></span><br />

        <span class="de"><strong>Bio</strong> :<br /><?php echo $author_info->description ; ?></span>
        <div class="clear">&nbsp;</div>

    <?php 
    }
    echo '</div>';
} else {
    echo 'No authors found';
}
?>

<?php /* WHAT DO I PUT HERE TO CREATE THE PAGINATION LINKS? */ ?>

如果你正在寻找的Ajax然后点击这里查看 wordpress.stackexchange.com/questions/113379/...
萨比尔·阿卜杜勒·谢赫Gafoor

Answers:


17

这应该使您真正接近。我没有测试过,但是它几乎与我使用过几次的设置相同。

/*
 * We start by doing a query to retrieve all users
 * We need a total user count so that we can calculate how many pages there are
 */

$count_args  = array(
    'role'      => 'Subscriber',
    'fields'    => 'all_with_meta',
    'number'    => 999999      
);
$user_count_query = new WP_User_Query($count_args);
$user_count = $user_count_query->get_results();

// count the number of users found in the query
$total_users = $user_count ? count($user_count) : 1;

// grab the current page number and set to 1 if no page number is set
$page = isset($_GET['p']) ? $_GET['p'] : 1;

// how many users to show per page
$users_per_page = 5;

// calculate the total number of pages.
$total_pages = 1;
$offset = $users_per_page * ($page - 1);
$total_pages = ceil($total_users / $users_per_page);


// main user query
$args  = array(
    // search only for Authors role
    'role'      => 'Subscriber',
    // order results by display_name
    'orderby'   => 'display_name',
    // return all fields
    'fields'    => 'all_with_meta',
    'number'    => $users_per_page,
    'offset'    => $offset // skip the number of users that we have per page  
);

// Create the WP_User_Query object
$wp_user_query = new WP_User_Query($args);

// Get the results
$authors = $wp_user_query->get_results();

// check to see if we have users
if (!empty($authors))
{
    echo '<div class="author-entry">';
    // loop trough each author
    foreach ($authors as $author)
    {
        $author_info = get_userdata($author->ID); ?>

        <span style="float:left;padding:0 5px 0 0;"><?php echo get_avatar( $author->ID, 50 ); /* http://codex.wordpress.org/Function_Reference/get_avatar */ ?></span>
        <span class="fn"><strong>First name</strong> : <?php echo $author_info->first_name; ?></span><br />
        <span class="ln"><strong>Last name</strong> : <?php echo $author_info->last_name; ?></span><br />
        <span class="em"><strong>Email address</strong> : <a href="mailto:<?php echo $author_info->user_email; ?>"><?php echo $author_info->user_email; ?></a></span><br />
        <span class="we"><strong>Website</strong> : <a href="<?php echo $author_info->user_url; ?>"><?php echo $author_info->user_url; ?></a></span><br />

        <span class="de"><strong>Bio</strong> :<br /><?php echo $author_info->description ; ?></span>
        <div class="clear">&nbsp;</div>

    <?php 
    }
    echo '</div>';
} else {
    echo 'No authors found';
}

// grab the current query parameters
$query_string = $_SERVER['QUERY_STRING'];

// The $base variable stores the complete URL to our page, including the current page arg

// if in the admin, your base should be the admin URL + your page
$base = admin_url('your-page-path') . '?' . remove_query_arg('p', $query_string) . '%_%';

// if on the front end, your base is the current page
//$base = get_permalink( get_the_ID() ) . '?' . remove_query_arg('p', $query_string) . '%_%';

echo paginate_links( array(
    'base' => $base, // the base URL, including query arg
    'format' => '&p=%#%', // this defines the query parameter that will be used, in this case "p"
    'prev_text' => __('&laquo; Previous'), // text for previous page
    'next_text' => __('Next &raquo;'), // text for next page
    'total' => $total_pages, // the total number of pages we have
    'current' => $page, // the current page
    'end_size' => 1,
    'mid_size' => 5,
));

2
如果代码会被拆分和解释,+ 1会很高兴:)
kaiser 2012年

5
在那里,添加了一些更好的注释并修复了一个或两个错误:)
Pippin 2012年

感谢@Pippin的帮助,我在演播室时会尝试一下。一个问题:我应在admin_url的“您的页面路径”部分添加什么?那是我网站的根吗?
Osu 2012年

是在管理员中还是在前端显示用户的页面?
2012年

1
有趣的方法。我注意到您在这里运行2个查询:第一个查询获得所有用户,第二个查询仅获得相应页面上的用户。如果仅使用1个查询,然后使用array_slice将结果分成页面,它的性能会更好吗?似乎由于您要对同一数据执行2个不同的查询,因此删除一个查询可以节省一些性能。
codecribblr 2015年

11

您真的不应该使用皮蓬的答案。查询效率很低。$user_count_query在该示例中,使用所有用户字段,最多可以将999,999个用户从数据库返回到脚本。如果您的站点足够大,这肯定会影响PHP的内存和/或时间限制。

但这可能是2012年的唯一解决方案。

这是一种更好的方法。在此示例中,我只有下一页和上一页,但是如果您确实需要编号的分页,可以使用变量进行构建。WordPress没有与WP_User_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页的示例:

用户表,从第2页开始


更新6/8/2018:如何添加页码代替下一个/上一个

如果要使用页码而不是下一个/上一个页面链接,可以通过以下方法进行设置。请注意,您将需要用页面链接替换数字,在此示例中,它们将不可单击(基于https://stackoverflow.com/a/11274294/470480,已修改为显示一致数量的中间数字,而不添加除非页面实际被跳过,否则为“ ...”。

您也可以看到我的gist文件,其中包含用于此目的的可重用功能。

$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]

我同意。Pippin的答案要求在数据库上命中2个命中点,如果可能应避免。
相扑

1
@ radley-sustaire,您好,这是一个不错的解决方案,但我想知道是否有办法将“每6个用户显示2个”部分更改为每页的实际用户范围。因此,类似于第1页的“显示1-2 of 6”,第2页的“显示3-4 of 6”和第3页的“ 6 of 5-6”。目前,它仅显示“ 6之2”所有页面。
damienoneill2001 '18

1
@ damienoneill2001这是一个好主意,您可以从以下类似开始:$start_user_num = (($current_page-1) * $users_per_page) + 1;$end_user_num = $start_user_num + count($users->get_results());
Radley Sustaire '18

@RadleySustaire很好,谢谢。起初,我收到以下错误:Call to a member function get_results() on a non-object所以我修改$end_user_number,以$start_user_num + ($users_per_page-1);和解决的问题。再次感谢!
damienoneill2001 '18

原来我很快就谈到了。当我到达不包含用户完整列表的最后一页时,很显然它$end_user_number在我的解决方案中显示了错误的数字。回到画板,哈!
damienoneill2001 '18

1

应该给@ radley-sustaire完整的信,这是他的答案,但是我发现它有一个小故障,因此我在这里分享我的答案。

在我的版本中,我还按位置,关键字等过滤结果,因此某些页面的结果少于'$ users_per_page'var。因此,例如,如果将我的每页用户数设置为显示10,但过滤器的结果仅返回3个用户,则页面顶部显示“显示3个用户中的10个”。显然,这没有任何意义,因此我添加了一个简单的“ if”语句来检查结果计数是否高于“ $ users_per_page”变量。

Radley,如果您通过更新来编辑答案,我会很高兴将其投票为正确答案,因为我认为它比Pippin的解决方案更好。

因此,这是任何需要它的人的最终代码。

<?php

// Pagination vars
$current_page = get_query_var('paged') ? (int) get_query_var('paged') : 1;
$users_per_page = 10;

$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

if ($total_users < $users_per_page) {$users_per_page = $total_users;}

?>
    <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>
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.