HomeAcademyHow to Load WordPress Posts Using Ajax

How to Load WordPress Posts Using Ajax

While working on a WordPress-powered website, sometimes you may come across a situation where you want to load WordPress posts with Ajax. In this tutorial, we will achieve it without pagination links. Instead, it will have a ‘Load More’ button/link, and clicking it will display the next set of posts. This process continues until all posts are shown.

https://9f887099d17810705b680cd9ec500266.safeframe.googlesyndication.com/safeframe/1-0-44/html/container.html

To see it in action, let’s assume you have a couple of posts and need to display 2 of them the first time. Then by clicking on ‘Load More’ the next 2 posts should display. And it will continue until the last post.

https://9f887099d17810705b680cd9ec500266.safeframe.googlesyndication.com/safeframe/1-0-44/html/container.html
Ezoic
  1. xPlayUnmuteFullscreenhttps://imasdk.googleapis.com/js/core/bridge3.695.1_en.html#fid=goog_1494951050Advertisement: 0:26
    1. Now Playing

x

video of: How to make webpages load faster in Blogger and WordPress _ Instant.Page

Play Video

How to make webpages load faster in Blogger and WordPress _ Instant. Page

Share

Watch on

Humix

How to make webpages load faster in Blogger and WordPress _ Instant. Page

This approach is useful as your web page will not refresh to view the next set of articles. Instead, it just appends the next posts in the DOM without reloading the page. We will keep loading WordPress posts into the div container using Ajax and jQuery. It improves the UX and also reduces server load.

That being said, let’s see how to load posts with Ajax and jQuery in WordPress.

Getting Started

To recap the flow, when someone visits your page for the first time, you need to show a few posts. Thereafter, subsequent posts will be displayed when you click the ‘Load More’ button.

Ezoic

For this, I will write the code in a custom page template. Create a new page called ‘Blog’ in the backend. Now, to display your posts on this page, create a custom template page-blog.php in your active theme’s directory. I kept the name as page-blog.php follows: the template hierarchy, which suggests the format as a page-{slug}.php. Adjust this slug as needed.

Let’s display the first 2 posts on the blog page. Using the WP_Query class, you can do it as shown below. Add the following code to the custom template.

<?php
$args = array(
    'post_type' => 'post',
    'post_status' => 'publish',
    'posts_per_page' => '2',
    'paged' => 1,
);
$blog_posts = new WP_Query( $args );
?>
<div class="entry-content">
    <?php if ( $blog_posts->have_posts() ) : ?>
        <div class="blog-posts">
            <?php while ( $blog_posts->have_posts() ) : $blog_posts->the_post(); ?>
                <h2><?php the_title(); ?></h2>
                <?php the_excerpt(); ?>
            <?php endwhile; ?>
            <?php wp_reset_postdata(); ?>
        </div>
        <div class="loadmore">Load More...</div>
    <?php endif; ?>
</div><!-- .entry-content -->

Here, I used the ‘paged’ key with the value ‘1’. The ‘paged’ variable is a key used in WordPress for pagination. The ‘paged' => 1 means the first page.

I also added the div element with the class loadmore and text ‘Load More’. Using a given class, you can add styling to this container. On clicking ‘Load More’, I’ll send an Ajax request, fetch the next set of posts, and append the response to the div with the class ‘blog-posts’.

Note: You can also use the same technique for the custom post types. Notice that I am passing post_type as an argument to WP_Query.

Ezoic

Load WordPress Posts with Ajax

Next, to integrate Ajax, include a custom.js file in the WordPress environment. Create this file inside the js directory and add the code below to the functions.php file.

function blog_scripts() {
    // Register the script
    wp_register_script( 'custom-script', get_stylesheet_directory_uri(). '/js/custom.js', array('jquery'), false, true );
 
    // Localize the script with new data
    $script_data_array = array(
        'ajaxurl' => admin_url( 'admin-ajax.php' ),
        'security' => wp_create_nonce( 'load_more_posts' ),
    );
    wp_localize_script( 'custom-script', 'blog', $script_data_array );
 
    // Enqueued script with localized data.
    wp_enqueue_script( 'custom-script' );
}
add_action( 'wp_enqueue_scripts', 'blog_scripts' );

This code will be included custom.js in the WordPress environment. I’m also passing 2 values to it.

Ezoic
  • ajaxurl In WordPress, you must use the admin-ajax.php URL to make an Ajax request. I set this URL to the ajaxurl key.
  • security : It’ll hold a nonce to avoid CSRF attacks.

Next, let’s write a jQuery code that handles the following stuff.

  • Give an Ajax call along with a few values.
  • Receives the response.
  • Append the response to the div having a ‘blog-posts’ class.
  • Hide the ‘Load More’ button when receiving an empty response.

custom.js

var page = 2;
jQuery(function($) {
    $('body').on('click', '.loadmore', function() {
        var data = {
            'action': 'load_posts_by_ajax',
            'page': page,
            'security': blog.security
        };
 
        $.post(blog.ajaxurl, data, function(response) {
            if($.trim(response) != '') {
                $('.blog-posts').append(response);
                page++;
            } else {
                $('.loadmore').hide();
            }
        });
    });
});

In the above code, I declared a JavaScript variable ‘page’ with an initial value of 2. This is because we need to get the posts starting from the second page (the posts on the first page are already displayed). I am incrementing this ‘page’ variable after receiving the Ajax response, which will give us the next page of records.

I used the action parameter ‘load_posts_by_ajax’, which needs to be mapped to WordPress actions. Open your functions.php file and add the lines below to it.

add_action('wp_ajax_load_posts_by_ajax', 'load_posts_by_ajax_callback');
add_action('wp_ajax_nopriv_load_posts_by_ajax', 'load_posts_by_ajax_callback');

The ‘wp_ajax_{action}’ fires an Ajax action, which refers to the callback function, which is ‘load_posts_by_ajax_callback’. The ‘wp_ajax_nopriv_{action}’ executes Ajax action for users that are not logged in. Let’s define this method in the functions.php file.

Ezoic
<?php
...
function load_posts_by_ajax_callback() {
    check_ajax_referer('load_more_posts', 'security');
    $args = array(
        'post_type' => 'post',
        'post_status' => 'publish',
        'posts_per_page' => '2',
        'paged' => $_POST['page'],
    );
    $blog_posts = new WP_Query( $args );
    ?>
 
    <?php if ( $blog_posts->have_posts() ) : ?>
        <?php while ( $blog_posts->have_posts() ) : $blog_posts->the_post(); ?>
            <h2><?php the_title(); ?></h2>
            <?php the_excerpt(); ?>
        <?php endwhile; ?>
        <?php wp_reset_postdata(); ?>
    <?php endif; ?>
    <?php
    wp_die();
}

This code uses the ‘page’ value for the ‘paged’ parameter. It fetches posts, loops through it, and builds the output.

Now, when you click on the ‘Load More’ button, it will load the next posts and return the response. The ‘Load More’ container will remain until you have all your posts.

I hope you learned how to load WordPress posts with Ajax and jQuery. You should now be able to easily integrate it into your WordPress projects. All you need to do is adjust some styling to match your theme, and you might change the value for posts_per_page.

Share: