Introduction
In this tutorial, you will learn about implementing the “Load More users in WordPress” functionality. Another term used is Ajax load more users in WordPress. We will use jquery and ajax. If you are not familiar with jquery and ajax, You can learn jquery from here.
What is ajax load more?
Ajax Load More is a technique used in web development to dynamically load additional content onto a webpage without requiring a full page reload. It allows users to retrieve and display additional data by clicking on a button or scrolling to a certain point on the page.
The term “Ajax” stands for Asynchronous JavaScript and XML, and it refers to a set of web development techniques that enable the exchange of data between the web browser and the server without requiring a complete page refresh. This allows for a smoother and more interactive user experience.
In the context of “Load More,” Ajax Load More is typically implemented to fetch additional content from the server and append it to the existing content on the page. For example, on a blog or an e-commerce website, you might have a list of items initially displayed, and as the user clicks on a “Load More” button, more items are loaded and added to the existing list without reloading the entire page.
Ajax Load More functionality is commonly implemented using JavaScript and the XMLHttpRequest or fetch API to send asynchronous requests to the server. The server typically responds with the additional data, usually in a format like JSON or XML, which is then parsed and dynamically inserted into the HTML structure of the page using JavaScript.
This technique provides a more efficient and seamless way to load and display content, as it avoids the need to load large amounts of data upfront and can enhance the overall performance and user experience of a website.
As simple as 1, 2, 3. Let’s begin our tutorial on Ajax load more for users. To do this, you must complete each of the stages listed below in order:
Create the layout (Page Template)
In web development, the very first step always starts with the designing part. In our tutorial, we will also start with the UI (design). We will make four <div>s in a row and show four users in those divs. After that, there will be a link to load more users.
Make a template in your WordPress theme for example loadmoreusers.php and then use the following code in that template.
<div class="dcs_outerdiv">
<div class="container">
<div class="row">
<h4>Users</h4>
<div class="col-sm-12 dcs_full_div">
<?php
$args = array (
'role'=> 'subscriber',
'number' =>'4',
'offset' =>'0'
);
$user_query = new WP_User_Query( $args );
if ( ! empty( $user_query->results ) ) {
foreach ( $user_query->results as $user )
{
$single = true;
$user_info = get_userdata($user->ID);
$first_name = $user_info->first_name;
$last_name = $user_info->last_name;
?>
<div class="col-sm-3 dcs_attach_more">
<p>First Name : <?php echo $first_name; ?></p>
<p>Last Name : <?php echo $last_name; ?></p>
<hr class="border"></hr>
</div>
<?php
}
}
else {
// echo something if there are no users.
} ?>
<div class="load_me_here"></div>
</div>
<a class="dcs_loadmore" href="">Load More</a>
</div>
</div>
</div>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script>var ajaxurl= '<?php echo admin_url( 'admin-ajax.php' ) ?>'</script>
<script type="text/javascript">
offset = 4;
jQuery(".dcs_loadmore").click(function(event) {
event.preventDefault();
jQuery.ajax({
type: "POST",
url: ajaxurl,
data: ({ action: "loadMore_users", offset : offset}),
success: function(response) {
if(response !='0'){
offset = offset + 4;
jQuery('.load_me_here').append(response);
}else{
jQuery('.load_me_here').append('<p class="dcs_para_center">No More Users to display...</p>');
jQuery('.dcs_loadmore').hide();
return false;
}
},
});
});
</script>
This code will make a template. Let me explain the code.
- The very first section is used to make the HTML view for the frontend (i.e UI for the page).
- After that, a script is written to call the ajax function when the link (load more users) is clicked. At the click of that link, we are passing the variable offset which contains the value. This is because we had already shown the previous four users on our page in HTML. So after ajax, the next four users should be shown.
Make a page in admin
Now you have to make a new page in the WordPress backend (admin dashboard). We are assuming that you very well know how to make a page in WordPress with a chosen template. If you don’t know how to make a page with a template, click here to refer the WordPress documentation. If you are ready with the page at the backend, go ahead to the next step.
Add Ajax Request
Now copy the following code into your theme’s functions.php file. In this function, we have used almost the same code as we used in the template as we are going to append a similar view for the next four users. The next four users will be fetched from DB and passed the data to the ajax callback function from this function. Ajax callback function will read the response from the function and then the script will load the response in the given div as code is bellowed.
<?php
/*--function for loads more users--*/
add_action('wp_ajax_loadMore_users', 'loadMore_users');
add_action('wp_ajax_nopriv_loadMore_users', 'loadMore_users'); // not really needed
function loadMore_users() {
global $wpdb;
extract($_POST);
$args = array (
'role'=> 'subscriber',
'number' =>'4',
'offset' => $offset
);
$user_query = new WP_User_Query( $args );
if ( ! empty( $user_query->results ) ) {
foreach ( $user_query->results as $user )
{
$single = true;
$user_info = get_userdata($user->ID);
$first_name = $user_info->first_name;
$last_name = $user_info->last_name;
?>
<div class="col-sm-3 dcs_attach_more">
<p>First Name : <?php echo $first_name; ?></p>
<p>Last Name : <?php echo $last_name; ?></p>
<hr class="border"></hr>
</div>
<?php
}
}
else { echo "0";}
die();
}
/*--function for loads more users--*/
Code Explanation
Above code is used in WordPress to handle an AJAX request for loading more users. Let’s break down the code and understand its functionality:
add_action(‘wp_ajax_loadMore_users’, ‘loadMore_users’);: This line adds an action hook to handle the AJAX request with the action name “loadMore_users” when it is triggered by an authenticated user.
add_action(‘wp_ajax_nopriv_loadMore_users’, ‘loadMore_users’);: This line adds an action hook to handle the AJAX request with the action name “loadMore_users” when it is triggered by an unauthenticated user. This line is not necessary if the functionality is intended for authenticated users only.
function loadMore_users() { … }: This line defines the callback function “loadMore_users” that will be executed when the AJAX request is triggered. The function retrieves and displays more users based on the provided parameters.
global $wpdb;: This line makes the WordPress database object available within the function.
extract($_POST);: This line extracts the values from the POST data sent in the AJAX request and creates corresponding variables. This allows easy access to the variables without using $_POST[‘variable_name’].
$args = array(…);: This line defines an array called “$args” that specifies the parameters for the WP_User_Query, which is used to query user data. In this case, it retrieves subscribers (users with the “subscriber” role) with a maximum of 4 users per query and an offset determined by the “offset” value from the AJAX request.
$user_query = new WP_User_Query($args);: This line creates a new instance of WP_User_Query using the defined arguments.
if (!empty($user_query->results)) { … }: This line checks if there are results from the user query.
foreach ($user_query->results as $user) { … }: This line iterates through each user returned by the query.
$single = true;: This line sets the variable $single to true.
$user_info = get_userdata($user->ID);: This line retrieves the user data for the current user in the loop based on their ID.
$first_name = $user_info->first_name;: This line retrieves the first name of the user from the user data.
$last_name = $user_info->last_name;: This line retrieves the last name of the user from the user data.
The following HTML code is a markup template that displays the first name and last name of each user in a <div> element with the class “col-sm-3 dcs_attach_more.” It uses PHP tags to echo the retrieved first name and last name.
else { echo “0”; }: If there are no results from the user query, this line echoes the string “0”.
die();: This line terminates the PHP execution, ensuring that only the desired response is sent back as a result of the AJAX request.
Overall, this code handles an AJAX request triggered by a user interface action, retrieves more users based on the given parameters, and returns the user information in HTML format.
After the successful call to the ajax function in the above code, the view will be appended to the given div. If you don’t know what is the meaning of append and what is the purpose of append, you can read our tutorial for jQuery append and prepend function. Along with that, we have used another jQuery function hide(). This function is used to hide a particular tag with a given class, id, or even with the tag name.