-
-
Save ibrahimkholil/02549b2e54e57782d403a90aa736b07c to your computer and use it in GitHub Desktop.
Pagination with WP_User_Query object
This file contains 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>'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment