maximeverrette
8/3/2018 - 5:59 PM

Listing de users avec pagination

add_shortcode( 'list_ambassadors', 'render_ambassadors' );
function render_ambassadors() {
	//Settings
	$role = "ambassador";
	$users_per_page = 1; // how many users to show per page
	
	$count_args  = array(
		'role'      => $role,
		'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 = get_query_var('paged') ? get_query_var('paged') : 1;

	// 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(
		'role'      => $role,
		'orderby'   => 'display_name', // order results by display_name
		'fields'    => 'all_with_meta', // return all fields
		'number'    => $users_per_page,
		'offset'    => $offset, // skip the number of users that we have per page  
		'meta_key' => 'last_name',
    'orderby' => 'meta_value',
    'order' => 'ASC'
	);

	// Create the WP_User_Query object
	$wp_user_query = new WP_User_Query($args);
	
	// Get the results
	$users = $wp_user_query->get_results();

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

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

				<span class="de"><strong>Bio</strong> :<br /><?php echo $user_info->description ; ?></span>
				<div class="clear">&nbsp;</div>
			<?php 
			}
		echo '</div>';
	} else {
		echo 'No ambassadors found';
	}
	
	echo paginate_links( array(
		'base' => get_permalink( get_the_ID() ) . 'page/%#%', // the base URL, including query arg
		'format' => '/page/%#%', // 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,
	));
}