¿Cómo mostrar los enlaces de paginación para WP_User_Query?

9

Creo que estoy a punto de lograrlo, pero no puedo hacer que aparezcan los enlaces de paginación para un directorio de autores que estoy creando.

Mi código está debajo, pero no sé cómo hacer que funcionen los enlaces para navegar entre las páginas de los autores. ¿Alguien puede ayudarme? Tengo la sensación de que esto podría ser útil, pero no sé cómo implementarlo:

paginate_links ()

Gracias

Osu

    <?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? */ ?>
    
pregunta Osu 04.07.2012 - 15:42

3 respuestas

16

Esto debería acercarte mucho. No lo he probado, pero es casi idéntico a una configuración que he usado varias veces.

/*
 * 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,
));
    
respondido por el Pippin 04.07.2012 - 17:03
6

Realmente no deberías usar la respuesta de Pippin. La consulta es muy ineficiente. $user_count_query en el ejemplo puede devolver hasta 999,999 usuarios desde su base de datos a su script, con todos los campos de usuario. Esto seguramente afectará la memoria y / o los límites de tiempo para PHP si / cuando su sitio crezca lo suficiente.

Pero esa pudo haber sido la única solución en 2012.

Aquí hay una mejor manera de hacerlo. En este ejemplo, solo tengo página siguiente y anterior pero si necesita paginación numerada, las variables están ahí para construirlo. WordPress no tiene una función de paginación que sea compatible con WP_User_Query (que yo sepa)

<?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>

Ejemplo que muestra la página 2:

Actualización6/8/2018:cómoagregarnúmerosdepáginaenlugardeSiguiente/Anterior

Sideseatenernúmerosdepáginaenlugardelosenlacesdelapáginasiguiente/anterior,aquíescómopuedeconfigurareso.Tengaencuentaquedeberáreemplazarlosnúmerosconenlacesdepágina,nosepodráhacerclicenesteejemplo(basadoen enlace , modificado para mostrar una cantidad constante de números intermedios y no agregar el "..." a menos que se omita una página).

También puede ver mi archivo gist que contiene una función reutilizable para este fin.

$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} ";

Salida (de la página 1 a 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]
    
respondido por el Radley Sustaire 14.05.2017 - 04:10
1

El crédito completo debería ir a @ radley-sustaire por su respuesta, pero detecté un pequeño problema técnico, así que estoy compartiendo mi versión de la respuesta aquí.

Con mi versión también estaba filtrando los resultados por ubicación, palabra clave, etc., por lo que algunas páginas tuvieron menos resultados que la var. '$ users_per_page'. Así, por ejemplo, si mis usuarios por página se configuraron para mostrar 10, pero los resultados del filtro solo obtuvieron 3 usuarios, obtuve 'Mostrando 10 de 3 usuarios' en la parte superior de la página. Obviamente, esto no tenía sentido, así que agregué una simple declaración "si" para verificar si el recuento de resultados era mayor que la variable '$ users_per_page'.

Radley, si edita su respuesta con la actualización, la votaré como la respuesta correcta, ya que creo que es mejor que la solución de Pippin.

Así que este es el código final para cualquier persona que lo quiera.

<?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>
    
respondido por el The Sumo 21.08.2017 - 09:56

Lea otras preguntas en las etiquetas