You are currently viewing Load More Pages with AJAX in WordPress, without page refreshing (Solved)

Load More Pages with AJAX in WordPress, without page refreshing (Solved)

In this article, we’ll explore how to Load More Pages with AJAX in WordPress, providing a fast and seamless browsing experience without the annoyance of page refreshes. No more waiting for entire pages to reload – just fast, seamless browsing.

If you’ve been on the search for an easy way to load more content on your WordPress site without refreshing, you’re in the right place. Let’s dive into the code and make your website more responsive and enjoyable for everyone. Get ready to level up your user experience!

Load More Pages with AJAX in WordPress without page refreshing

2 Steps to add Load More Pages with AJAX in WordPress, without page refreshing

  1. Open your theme’s functions.php file.
  2. Add the following code:
function services_provide_posts_shortcode_with_ReadMore() {
    $args = array(
        'category_name' => 'services-we-provide',
        'posts_per_page' => 8, // Show only 3 posts initially
        'orderby' => 'title',
        'order' => 'ASC',
    );

    $query = new WP_Query($args);

    if ($query->have_posts()) :
        $output = '<div class="services-provide-posts">';
        $output .= '<div class="services-provide-row">';
        $count = 0;

        while ($query->have_posts()) : $query->the_post();
            $excerpt = wp_trim_words(get_the_excerpt(), 15);
            $output .= '<div class="services-provide-col">';
            $output .= '<div class="services-provide-post">';
            $output .= '<h3>' . wp_trim_words(get_the_title(), 2) . '</h3>';
            $output .= '<div class="services-provide-excerpt">' . $excerpt . '</div>';
            $output .= '<a href="' . get_permalink() . '" class="services-provide-read-more">Explore Now</a>';
            $output .= '</div>';
            $output .= '</div>';
            $count++;
        endwhile;
//echo $query->found_posts;
        $output .= '</div>';
        $output .= '<div style="text-align:center;"><button class="read-more-button button">Load More</button></div>';
        $output .= '</div>';
        $output .= '<script>
    jQuery(document).ready(function ($) {
        var page = 2;
        var loading = false;
        var noMoreItems = false;
        var buttonText = "Load More";
        var initialPostCount = ' . $query->found_posts . '; // Total number of posts

        function loadPosts() {
            if (loading || noMoreItems) return;

            loading = true;
            $(".read-more-button").text("Loading Data.Please Wait...").prop("disabled", true); // Change button text to "Loading..." and disable the button

            $.ajax({
                url: "' . admin_url('admin-ajax.php') . '",
                type: "post",
                data: {
                    action: "load_more_services_posts",
                    page: page,
                },
                success: function (response) {
                    loading = false;

                    if (response) {
                        $(".services-provide-row").append(response);
                        page++;

                        // Count the number of displayed posts
                        var displayedPostCount = $(".services-provide-col").length;
      //console.log(displayedPostCount);

                        if (displayedPostCount >= initialPostCount) {
                            noMoreItems = true;
                        }
                    } else {
                        noMoreItems = true;
                    }

                    $(".read-more-button").text(noMoreItems ? "No more Data" : buttonText).prop("disabled", noMoreItems); // Change button text and disable the button
                },
                error: function () {
                    loading = false;
                    $(".read-more-button").text(buttonText).prop("disabled", false); // Change button text back to original and enable the button on error
                },
            });
        }

        // Load more posts when clicking "Read More" button
        $(".read-more-button").on("click", function () {
            loadPosts();
        });
    });
</script>
   ';
    endif;

    wp_reset_postdata();

    return $output;
}
add_shortcode('services_provide_posts_with_ReadMore', 'services_provide_posts_shortcode_with_ReadMore');

add_action('wp_ajax_load_more_services_posts', 'load_more_services_posts');
add_action('wp_ajax_nopriv_load_more_services_posts', 'load_more_services_posts');

function load_more_services_posts() {
   $page = isset($_POST['page']) ? intval($_POST['page']) : 1;
  // Change this to load a different number of posts in each AJAX call
    $posts_per_page = 8;

    $args = array(
        'category_name' => 'services-we-provide',
        'posts_per_page' => $posts_per_page,
        'orderby' => 'title',
        'order' => 'ASC',
        'paged' => $page,
    );

    $query = new WP_Query($args);

    if ($query->have_posts()) {
        while ($query->have_posts()) {
            $query->the_post();
            $excerpt = wp_trim_words(get_the_excerpt(), 15);
            echo '<div class="services-provide-col">';
            echo '<div class="services-provide-post">';
            echo '<h3>' . wp_trim_words(get_the_title(), 2) . '</h3>';
            echo '<div class="services-provide-excerpt">' . $excerpt . '</div>';
            echo '<a href="' . get_permalink() . '" class="services-provide-read-more">Explore Now</a>';
            echo '</div>';
            echo '</div>';
        }
        wp_reset_postdata();
    } else {
        echo ''; // Return an empty string if no more items
    }

    wp_die();
}

Add this CSS on the style.css


/**shortcode css-start**/


.services-provide-posts {
    display: block;
    margin: 0;
    padding: 0;
}

.services-provide-row {
    display: block;
    margin: 0;
    padding: 0;
}

.services-provide-col {
    display: inline-block;
    width: 100%;
    margin: 0;
    padding: 10px;
    box-sizing: border-box;
    height: auto;
}

.services-provide-post {
    border: 1px solid #ddd;
    margin-bottom: 20px;
    padding: 15px;
    height: auto;
}

.services-provide-post h3 {
    margin: 0 0 10px;
}

.services-provide-excerpt {
    margin-bottom: 10px;
}

.services-provide-read-more {
    display: inline-block;
 border: 1px solid #14a74f;
    color: #14a74f;
    padding: 5px 10px;
    text-decoration: none!important;
}

.services-provide-read-more:hover {
    background-color: #14a74f;
 color:white;
}

/* Small screens */
@media only screen and (max-width: 767px) {
    .services-provide-col {
        width: 100%;
    }
}

/* Medium screens */
@media only screen and (min-width: 768px) and (max-width: 991px) {
    .services-provide-col {
        width: 50%;
    }
}

/* Large screens */
@media only screen and (min-width: 992px) {
    .services-provide-col {
        width: 25%;
    }
}

In conclusion, implementing AJAX for loading more pages in WordPress is a game-changer for user experience. By eliminating the need for page refreshes, your website becomes more dynamic and user-friendly. Now that you have the tools and insights to seamlessly integrate this feature, take your WordPress site to new heights. Enhance user engagement, reduce load times, and keep visitors hooked with the power of AJAX. As you Load More Pages with AJAX in WordPress, you’re not just optimizing your site – you’re crafting a smoother, more enjoyable journey for your audience.

Hope you will find this code helpful to add Load More Pages with AJAX in WordPress, without page refreshing. If you are facing any error drop the comment below. Our professional team will give you the solution in a short turn.

Contact SKFreelancers Team

Join Us on Facebook

Leave a Reply