WordPress Tutorials

Add Infinite Scroll to WordPress Without a Plugin

Infinite scroll loads the next set of posts automatically as a visitor nears the bottom of the page. There is no reload and no click needed to keep reading. This guide shows you how to add infinite scroll WordPress without plugin support, using the built in AJAX system and WP_Query with a small amount of PHP and JavaScript.

The build has four parts: a template container, an AJAX handler, an enqueued script, and JavaScript that watches scrolling. Join them safely, stop at the last page, and keep the archive usable for search engines and keyboard users.

What Is Infinite Scroll and Where Does It Fit?

Infinite scroll replaces click through pages with one long stream. When the visitor scrolls close to the end of the loaded posts, the browser requests the next page in the background and appends those posts below the ones already on screen. A loading message shows that more content is coming.

It fits best where browsing matters more than finding one exact item. Blog archives, news feeds, galleries, and WooCommerce shop grids suit it well because visitors scan many items in one visit. It fits poorly where people must reach the footer, compare items across pages, or return to an exact spot after opening a post.

What Are the Trade Offs You Should Weigh First?

The smooth feel carries real costs. Search engines need crawlable links to reach older posts, so keep real pagination links in the page even when the script hides them visually. The footer also becomes nearly unreachable because new posts keep pushing it down, so contact details and legal links may never be seen.

Accessibility and the back button need thought too. Screen reader users should be told new content arrived, keyboard users need to move through a growing list without losing their place, and a visitor who opens a post then presses back may land at the top. For many sites numbered pagination is simply better. If that sounds closer to your needs, follow our numbered pagination tutorial instead.

How Does a Hand Built Infinite Scroll Work?

Your template prints the first page of posts inside a container with a loader below it. WordPress loads a script and hands it the AJAX address, a nonce, the current page, and the total pages. Near the bottom, the script checks that it is not already loading and that pages remain, then requests the next page. PHP verifies the nonce, queries those posts, and returns their HTML. The script appends the HTML and waits for the next scroll.

  • Template: a posts container and a loader with stable IDs.
  • PHP: an AJAX handler that queries posts and returns markup.
  • Enqueue: a script loaded with wp_localize_script data.
  • JavaScript: scroll detection guarded by a loading flag.

How Do You Add the HTML Container and Loader?

Start in the template that lists posts, such as index.php or archive.php, inside a child theme so updates do not erase your work. Our guide to create a WordPress child theme covers that setup. Wrap the loop output in a container and add a loader after it.

<div id="post-stream">
  <?php while (have_posts()) : the_post(); ?>
    <article>
      <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
      <?php the_excerpt(); ?>
    </article>
  <?php endwhile; ?>
</div>
<div id="stream-loader" hidden>Loading more posts...</div>
<?php the_posts_pagination(); ?>

The container ID matters because the script appends new posts to exactly that element. Keep the pagination call in place and hide it with CSS if you wish. The links must stay in the HTML so crawlers and visitors without JavaScript can still reach older posts.

How Do You Build the AJAX Handler in PHP?

Add the handler to your child theme functions.php file or a small custom plugin. Register both the logged in hook and the nopriv hook. The nopriv hook is the one most people forget, and without it the feature fails silently for logged out visitors.

add_action('wp_ajax_load_more_posts', 'vutg_load_more_posts');
add_action('wp_ajax_nopriv_load_more_posts', 'vutg_load_more_posts');

function vutg_load_more_posts() {
    check_ajax_referer('vutg_stream_nonce', 'nonce');
    $paged = isset($_POST['page']) ? absint($_POST['page']) : 1;
    $args = array(
        'post_type' => 'post',
        'posts_per_page' => 10,
        'paged' => $paged,
        'post_status' => 'publish',
    );
    if (!empty($_POST['cat'])) {
        $args['cat'] = absint($_POST['cat']);
    }
    if (!empty($_POST['s'])) {
        $args['s'] = sanitize_text_field(wp_unslash($_POST['s']));
    }
    $query = new WP_Query($args);
    if ($query->have_posts()) {
        while ($query->have_posts()) {
            $query->the_post();
            ?>
            <article>
              <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
              <?php the_excerpt(); ?>
            </article>
            <?php
        }
    }
    wp_reset_postdata();
    wp_die();
}

Three safety steps matter most. check_ajax_referer verifies the nonce so stray requests cannot trigger the handler freely. absint cleans the page number and category ID, while sanitize_text_field with wp_unslash cleans any search term. Never trust values from the browser. Finally, wp_die ends the request cleanly so no extra output corrupts your markup. See the wp_ajax action reference for the hook details.

Match the query to your archive. Posts per page, post type, and ordering must mirror the template. If page one shows ten posts and the AJAX query returns twelve, the stream will skip or repeat items.

How Do You Enqueue the Script and Pass the Data?

The script needs facts only WordPress knows. Load it with wp_enqueue_script, then attach a data object with wp_localize_script holding the AJAX address, a fresh nonce, the current page, and the maximum pages. Load it only on listing pages such as home, archives, and search.

add_action('wp_enqueue_scripts', 'vutg_stream_assets');
function vutg_stream_assets() {
    if (!is_home() && !is_archive() && !is_search()) {
        return;
    }
    wp_enqueue_script(
        'vutg-stream',
        get_stylesheet_directory_uri() . '/js/stream.js',
        array(),
        '1.0.0',
        true
    );
    global $wp_query;
    wp_localize_script('vutg-stream', 'vutgStream', array(
        'ajaxUrl' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('vutg_stream_nonce'),
        'page' => max(1, get_query_var('paged')),
        'maxPages' => (int) $wp_query->max_num_pages,
        'cat' => is_category() ? get_queried_object_id() : 0,
        'search' => is_search() ? get_search_query() : '',
    ));
}

The maximum pages value is essential. Without it the script cannot know when the archive ends and will request empty pages forever. The category and search values make the same script work beyond the homepage. Read more in the wp_localize_script reference. If the archive already feels sluggish, work through our guide on why a WordPress site runs slow first.

How Do You Detect Scrolling in JavaScript?

Create stream.js in a js folder inside your child theme. The script watches the scroll position and requests more posts within a few hundred pixels of the bottom. A loading flag blocks duplicate requests while one runs, which matters because scroll events fire many times per second.

document.addEventListener('DOMContentLoaded', function () {
  const stream = document.getElementById('post-stream');
  const loader = document.getElementById('stream-loader');
  if (!stream || !loader) return;
  let page = parseInt(vutgStream.page, 10);
  const maxPages = parseInt(vutgStream.maxPages, 10);
  let loading = false;

  function loadMore() {
    if (loading || page >= maxPages) return;
    loading = true;
    loader.hidden = false;
    page++;
    const body = new URLSearchParams({
      action: 'load_more_posts',
      nonce: vutgStream.nonce,
      page: page,
      cat: vutgStream.cat,
      s: vutgStream.search
    });
    fetch(vutgStream.ajaxUrl, {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: body
    })
      .then(function (res) { return res.text(); })
      .then(function (html) {
        if (html.trim()) {
          stream.insertAdjacentHTML('beforeend', html);
        }
      })
      .catch(function () { page--; })
      .finally(function () {
        loading = false;
        loader.hidden = true;
      });
  }

  window.addEventListener('scroll', function () {
    const nearBottom = window.innerHeight + window.scrollY >=
      document.body.offsetHeight-400;
    if (nearBottom) loadMore();
  }, { passive: true });
});

Note the order inside loadMore. It checks the flag and page limit first, sets loading to true, then increments the counter. On failure the catch block steps the counter back so no page is skipped. insertAdjacentHTML appends the new markup without disturbing posts already on screen, and the passive listener keeps scrolling smooth. Style the loader with CSS so it is easy to spot. Our tutorial on how to add custom CSS in WordPress covers the safe routes.

How Do You Make It Work on Categories, Archives, and Search?

A stream that works only on the homepage disappoints quickly. Category pages must load that category only, author archives must stay with that author, and search results must keep matching the term. The pattern never changes: detect the context in PHP, pass the value to JavaScript, and apply it again in the handler.

The code above already handles categories and search. Extend it the same way for tags, authors, or custom post types with one localized value and one matching query argument each. Sanitize every value on the server, and confirm max_num_pages reflects the filtered query. On archives the main query already accounts for the filter, so the value stays correct. Test each archive type separately.

How Do You Turn It Into a Load More Button Instead?

A Load More button is often the better compromise. Visitors choose when to load more, the footer stays reachable between clicks, keyboard users get a clear control, and the back button behaves better. Your PHP stays identical. Only the trigger changes.

<button id="load-more" type="button">Load more posts</button>

Place the button below the container and swap the scroll listener for a click listener calling the same loadMore function. Disable the button while loading and hide it when the counter reaches maxPages. You can even combine both: auto load the first few pages, then switch to the button so the footer becomes reachable.

How Do You Test It Before You Ship It?

Test on staging first, then repeat the checks live. Cover desktop and a real phone, and throttle the network once in your browser tools so you can watch the loader and confirm duplicate requests never fire.

  • Last page: requests stop at maxPages and the loader stays hidden.
  • No duplicates: titles never repeat and none are skipped.
  • Logged out: the stream works in a private window.
  • Mobile: touch scrolling loads smoothly with no layout jump.
  • Archives: category, search, and author pages load only their own posts.
  • Fallback: with JavaScript off, pagination links reach every page.

If testing feels slow, check hosting before blaming the script. Every request queries the database, so weak hosting shows up fast. Our web hosting guide explains what a plan needs to handle growing traffic.

What Mistakes Break Infinite Scroll Most Often?

Three mistakes cause most failures. Forgetting the nopriv hook makes the feature work for admins and fail for visitors. Skipping the max page check sends endless requests for pages that do not exist. Appending to the wrong container, usually after the template ID and script ID drift apart, drops posts into the footer or breaks the layout.

Other slips include mismatched posts per page values, a missing wp_die, and mismatched nonce names. In the network tab, a 400 response points to the action or nonce, 0 means no handler matched, and an empty 200 means the query found nothing.

Frequently Asked Questions

Does infinite scroll hurt WordPress SEO?

It can if crawlers cannot reach older posts. Keep pagination links in the HTML, keep each paginated page crawlable, and list posts in your sitemap. With those safeguards, the stream mainly changes how humans browse.

Can I use infinite scroll with WooCommerce shop pages?

Yes. Set the post type to product, match the shop ordering, and append to the products container. Keep the nonce, page guard, and loading flag, and test sorting and filtering carefully.

Why does it work for me but not for visitors?

That pattern almost always means the nopriv hook is missing. Register both hooks for the same action, clear cache, and retest logged out in a private window.

Should I choose infinite scroll or a Load More button?

Pick the button when the footer matters, when visitors compare items, or when accessibility is a priority. Pick automatic scrolling for feeds and galleries. Both share the same PHP handler.

Last updated: December 2026.

Hostinger - Get 20% OFF

Habib ur Rehman

Hello! I'm the founder of VU Tech Geek. As a BSCS graduate and experienced WordPress professional, I'm passionate about technology and education. My Virtual University journey has given me valuable insights and knowledge, which I love to share with fellow students.… More »

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button

Adblock Detected

Please consider supporting us by disabling your ad blocker