This is How to Add a Load More Button for a Custom Post Type in WordPress
As a WordPress developer, you may have encountered the need to display a large number of custom post type entries on a single page. While pagination is a common solution, it can sometimes disrupt the user experience, especially when users are trying to quickly browse through content.
This is where a "Load More" button can be a game-changer. By allowing users to fetch additional content on-demand, you can provide a smoother and more engaging browsing experience. In this article, we'll walk you through the step-by-step process of adding a load more button for a custom post type in WordPress.
Understanding the Load More Feature
The load more feature works by allowing users to click a button that triggers an AJAX request to fetch the next set of posts. When the AJAX request is successful, the new posts are then appended to the existing content on the page.
This approach has several benefits:
-
Improved User Experience: By avoiding the need for full page refreshes, the load more feature creates a more seamless and responsive user experience, allowing users to quickly browse through your content.
-
Reduced Server Load: Instead of loading all the posts at once, the load more feature only retrieves the necessary content, reducing the server load and improving the overall performance of your WordPress site.
-
Increased Engagement: The ability to quickly access more content can encourage users to spend more time on your site, leading to increased engagement and potentially improved conversion rates.
Step 1: Prepare the HTML Structure
To implement the load more feature, we'll start by creating the necessary HTML structure. Let's assume you have a custom post type called "My Custom Post Type" and you want to display the posts on a dedicated archive page.
<div class="my-custom-post-type-container">
<!-- Existing posts will be displayed here -->
</div>
<button id="toggle-more" class="load-more-button">Load More</button>
In this example, we have a container div that will hold the existing posts, and a button with the ID "toggle-more" that will trigger the load more functionality.
Step 2: Implement the JavaScript Logic
Next, we'll create the JavaScript code that will handle the click event on the load more button and make the AJAX request to fetch the next set of posts.
document.addEventListener('DOMContentLoaded', function() {
const container = document.querySelector('.my-custom-post-type-container');
const loadMoreButton = document.getElementById('toggle-more');
let currentPage = 1;
loadMoreButton.addEventListener('click', function() {
currentPage++;
loadMorePosts(currentPage);
});
function loadMorePosts(page) {
fetch(`/wp-admin/admin-ajax.php?action=load_more_posts&page=${page}&post_type=my-custom-post-type`, {
method: 'GET',
})
.then(response => response.text())
.then(data => {
container.insertAdjacentHTML('beforeend', data);
if (data.trim() === '') {
loadMoreButton.style.display = 'none';
}
})
.catch(error => {
console.error('Error fetching more posts:', error);
});
}
});
Here's a breakdown of what's happening in the JavaScript code:
- We first select the container div and the load more button using
document.querySelector
and document.getElementById
.
- We initialize a
currentPage
variable to keep track of the current page being displayed.
- We add a click event listener to the load more button that increments the
currentPage
variable and calls the loadMorePosts
function.
- The
loadMorePosts
function uses the fetch
API to make an AJAX request to the WordPress admin-ajax.php file, passing the current page number and the post type as query parameters.
- When the AJAX request is successful, the response is appended to the container div using
insertAdjacentHTML
. If the response is empty, we hide the load more button.
- If there's an error during the AJAX request, we log the error to the console.
Step 3: Create the WordPress Functions
Now, we need to create the necessary WordPress functions to handle the AJAX request and return the appropriate content.
add_action('wp_ajax_load_more_posts', 'load_more_posts');
add_action('wp_ajax_nopriv_load_more_posts', 'load_more_posts');
function load_more_posts() {
$page = isset($_GET['page']) ? absint($_GET['page']) : 1;
$post_type = isset($_GET['post_type']) ? sanitize_text_field($_GET['post_type']) : 'post';
$args = array(
'post_type' => $post_type,
'posts_per_page' => 3, // Change this to your desired number of posts per page
'paged' => $page,
);
$query = new WP_Query($args);
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
// Render the post content using your custom template
get_template_part('template-parts/content', 'my-custom-post-type');
}
wp_reset_postdata();
} else {
echo '';
}
wp_die();
}
In this code, we've added two action hooks: wp_ajax_load_more_posts
and wp_ajax_nopriv_load_more_posts
. These hooks ensure that the load_more_posts
function is called when the AJAX request is made, regardless of whether the user is logged in or not.
The load_more_posts
function does the following:
- It retrieves the current page number and the post type from the AJAX request.
- It sets up the
WP_Query
arguments, including the post type, the number of posts to display per page, and the current page number.
- It checks if there are any posts to display and, if so, renders the post content using a custom template part (in this case,
content-my-custom-post-type.php
).
- If there are no more posts to display, it outputs an empty string.
- Finally, it calls
wp_die()
to terminate the AJAX request.
Make sure to create the content-my-custom-post-type.php
template part and customize it to display your custom post type content as needed.
Styling the Load More Button
To make the load more button visually appealing, you can add some CSS styling. Here's an example:
.load-more-button {
display: block;
margin: 20px auto;
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
}
.load-more-button:hover {
background-color: #45a049;
}
This CSS code will center the load more button, give it a green color scheme, and add a hover effect to make it more visually appealing.
Get a Free AI Website Audit
Automatically identify UX and content issues affecting your conversion rates with Flowpoint's comprehensive AI-driven website audit.
Conclusion
By following the steps outlined in this article, you can easily add a load more button for your custom post type in WordPress. This feature will enhance the user experience on your site, allowing visitors to quickly browse through your content without the need for full page refreshes.
Remember, the code provided in this article is a starting point, and you may need to customize it further to fit the specific requirements of your WordPress project. If you have any questions or need further assistance, feel free to reach out to the Flowpoint.ai team, who can help you identify and fix any technical issues that may be impacting your website's conversion rates.
[Flowpoint.ai](https://flowpoint.ai