Created
May 29, 2018 12:49
-
-
Save mujahidi/276a4a77cfd31bcb049b69563ed3c888 to your computer and use it in GitHub Desktop.
Pagination with WP_User_Query object
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// number of users we want to show per page | |
$number = 10; | |
// to pinpoint the current pagination number | |
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1; | |
// count the number of users that should be passed over in the pages (offset) – this will take effect at the second page onwards. | |
$offset = ($paged - 1) * $number; | |
// query arguments per your specifications | |
$args = array( | |
'order' => 'asc', | |
'orderby' => 'display_name', | |
'meta_query' => array( | |
array( | |
'key' => 'first_name', | |
'value' => esc_attr($_GET['search']), | |
'compare' => 'LIKE' | |
), | |
) | |
); | |
// Create the WP_User_Query object to fetch total users without 'number' and 'offset' arguments | |
$total_users_query = new WP_User_Query($args); | |
$total_users = $total_users_query->total_users; | |
// Now add query arguments for pagination | |
$args['number'] = $number; | |
$args['offset'] = $offset; | |
// Create the WP_User_Query object again with updated arguments | |
$wp_user_query = new WP_User_Query($args); | |
// Get the results | |
$total_query = $wp_user_query->total_users; | |
$total_pages = intval($total_users / $number) + 1; | |
// Use the following with foreach() loop to display results as per your requirements | |
$user_query = $wp_user_query->get_results(); | |
//foreach( $user_query as $user ){ ... } | |
// for more about paginate_links() -- https://codex.wordpress.org/Function_Reference/paginate_links | |
if ($total_users >= $total_query) { | |
echo '<div id="pagination" class="clearfix um-members-pagi">'; | |
echo '<span class="pages">Pages:</span>'; | |
$current_page = max(1, get_query_var('paged')); | |
echo paginate_links(array( | |
'base' => get_pagenum_link(1) . '%_%', | |
'format' => 'page/%#%/', | |
'current' => $current_page, | |
'total' => $total_pages, | |
'prev_next' => true, | |
'show_all' => true, | |
'type' => 'plain', | |
)); | |
echo '</div>'; | |
} |
i'm using your solution but when click page 2, 3 ... wordpress show "Sorry, you are not allowed to access this page." Our link ...customers/page/2/
can you help me now ??
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
$total_pages
shows an extra page if the division is perfect. E.g 20 users, 10 per page, 3 pagesIt should be