Ajax Load More is a popular plugin for WordPress that allows you to load more posts on a page using ajax. Here’s an example of how you can use the plugin to load more custom post types:
- Install and activate the Ajax Load More plugin on your WordPress website.
- Create a new custom post type in your functions.php file or use a custom post type plugin
- Create a new template file (e.g. custom-post-type-ajax.php) for the custom post type and design it to display the posts as you want.
- In your template file where you want the load more button to appear, add the following shortcode:
[ajax_load_more post_type="custom_post_type" repeater="template_file" button_label="Load More"]
Where “custom_post_type” is the name of your custom post type, and “template_file” is the name of the template file you created in step 3.
- In your JavaScript file, you need to add the following code to handle the ajax request:
jQuery(document).ready(function($) { $('#ajax-load-more').on('click', function() { // Add your custom post type here var data = { 'action': 'load_more_custom_post_type', 'post_type': 'custom_post_type', 'offset': $('.custom-post-type-class').length }; $.post(ajaxurl, data, function(response) { // Append the response to the DOM $('.custom-post-type-container').append(response); }); }); });
6. In your theme’s functions.php, you need to add the following code to handle the ajax request on the server side:
function load_more_custom_post_type() { // Get the offset $offset = $_POST['offset']; // Get the custom post type $post_type = $_POST['post_type']; // Set the number of posts to load $post_per_page = 5; // Get the custom post type $args = array( 'post_type' => $post_type, 'offset' => $offset, 'posts_per_page' => $post_per_page ); $posts = get_posts($args); // Loop through the posts foreach ($posts as $post) {
function load_more_custom_post_type() {
// Get the offset
$offset = $_POST['offset'];
// Get the custom post type
$post_type = $_POST['post_type'];
// Set the number of posts to load
$post_per_page = 5;
// Get the custom post type
$args = array(
'post_type' => $post_type,
'offset' => $offset,
'posts_per_page' => $post_per_page
);
$posts = get_posts($args);
// Loop through the posts
foreach ($posts as $post) {
// Get the post ID
$post_id = $post->ID;
// Get the post content
$post_content = $post->post_content;
// Echo the post content
echo '
‘; echo $post_content; echo ”;
}
die();
}
add_action(‘wp_ajax_load_more_custom_post_type’, ‘load_more_custom_post_type’);
add_action(‘wp_ajax_nopriv_load_more_custom_post_type’, ‘load_more_custom_post_type’);
Last modified: January 13, 2023