Adding Infinite Scroll to WordPress Theme Without Plugins

Hello! In this article, we will show you how to add plugins to your WordPress theme. infinite scroll I'll explain how to add the (infinite scroll) feature. When I use this method in my own projects, I've seen great results in terms of both performance and user experience. Many resources online either focus on using plugins or offer methods that only work for index.php but cause problems on pages like category.php or author.php. This guide offers a customizable solution that works correctly on every page. For example, AdminLteWpTheme You can reference the source code; you'll find a working example there. If you're ready, let's get started!

Create a Child Theme First

Before adding this feature, subtheme I recommend creating a (child theme). This way, updates to your parent theme won't affect any customizations you've made. For steps to create a child theme, WordPress official documentation You can browse.

Step 1: Adding Code to the functions.php File

We'll create an AJAX-based function for infinite scrolling. Add the following code to your theme's (or child theme's) functions.php file:

// Infinite Scroll function wp_infinitepaginate() { $loop_dosyasi = $_POST['loop_file']; $page_no = $_POST['page_no']; $action = $_POST['what']; $value = $_POST['value']; if ($action == 'author_name') { $arg = array('author_name' => $value, 'paged' => $page_no, 'post_status' => 'publish'); } elseif ($action == 'category_name') { $arg = array('category_name' => $value, 'paged' => $page_no, 'post_status' => 'publish'); } elseif ($action == 'search') { $arg = array('s' => $value, 'paged' => $page_number, 'post_status' => 'publish'); } else { $arg = array('paged' => $page_id, 'post_status' => 'publish'); } # Load posts query_posts($arg); get_template_part($loop_dosyasi); exit; } add_action('wp_ajax_infinite_scroll', 'wp_infinitepaginate'); // For logged in users add_action('wp_ajax_nopriv_infinite_scroll', 'wp_infinitepaginate'); // For not logged in users

What Does This Code Do?

  • AJAX Request: This function runs when an AJAX request arrives and creates a loop from the specified file.
  • POST Data:
    • loop_file: The name of the loop file that will generate HTML codes.
    • page_no: Determines which page will be loaded.
    • what: Specifies the page type, such as category, author, or search.
    • value: Contains values such as category slug and author name.
  • Creating a QueryUsing :if conditions, query_posts parameters are created based on the desired page type. The loop file is then called with get_template_part.
  • AJAX SupportWith :add_action the function connects to WordPress's AJAX system (wp-admin/admin-ajax.php).

When I used this code in a blog project, I customized the what and value parameters to load the correct posts on category pages, which improved the user experience a lot.

Step 2: Creating a Loop File

Create a loop file in your theme's directory. You can specify any name you like, but be sure to pass it to the loop_file parameter in your AJAX request. I used loop.php as an example. This file will generate the HTML output for your posts. For example, you can copy the loop from your index.php file. Here AdminLteWpThemeAn example inspired by:

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
    <!-- Zaman çizelgesi etiketi -->
    <li class="time-label">
        <span class="bg-green"><?php the_time('d.m.Y'); ?></span>
    </li>
    <!-- Zaman çizelgesi öğesi -->
    <li>
        <i class="fa fa-newspaper-o bg-blue"></i>
        <div class="timeline-item">
            <span class="time"><i class="fa fa-clock-o"></i> <?php the_time('H:i'); ?></span>
            <h3 class="timeline-header"><a href="/en/</?php the_permalink(); ?>" alt="<?php the_title(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></h3>
            <div class="timeline-body">
                <div class="row">
                    <div class="col-lg-3 col-sm-4 col-xs-6">
                        <a href="/en/</?php the_permalink(); ?>" title="<?php the_title(); ?>">
                            <?php if (has_post_thumbnail()) {
                                $resim_yolu = wp_get_attachment_image_src(get_post_thumbnail_id(), 'medium');
                            ?>
                                <img src="<?php echo $resim_yolu[0]; ?>" class="img-responsive" alt="<?php the_title(); ?>" title="<?php the_title(); ?>" />
                            <?php } ?>
                        </a>
                    </div>
                    <div class="col-lg-9 col-sm-8 col-xs-6">
                        <?php the_excerpt_rss(); ?>
                        <div style="margin-top: 10px">
                            <a class="btn btn-primary btn-xs" href="/en/</?php the_permalink(); ?>" title="<?php the_title(); ?>">Read more</a>
                        </div>
                    </div>
                </div>
            </div>
            <div class="timeline-footer">
                <i class="fa fa-user"></i> <a href="/en/</?php echo esc_url(get_author_posts_url(get_the_author_meta('ID'))); ?>" title="<?php the_author(); ?>"><?php the_author(); ?></a> | 
                <i class="fa fa-folder-open"></i> | 
                <i class="fa fa-comments"></i> <?php comments_number('0 yorum', '1 yorum', '% yorum'); ?>
            </div>
        </div>
    </li>
    <!-- Zaman çizelgesi öğesi sonu -->

When I used this file on a news site, I found that my posts loaded visually and neatly. You can customize the loop file to create a design that matches your theme.

Step 3: Adding JavaScript Code

Finally, to enable infinite scrolling, you need to add JavaScript code to files like index.php and category.php. The following code loads new posts when the page is scrolled down:

<script type="text/javascript">
jQuery(document).ready(function($) {
    var count = 2; // Başlangıç sayfası (2. sayfa)
    var total = <?php echo $wp_query->max_num_pages; ?>; // Toplam sayfa sayısı
    $(window).scroll(function() {
        if ($(window).scrollTop() == $(document).height() - $(window).height()) {
            if (count > total) {
                return false; // Tüm sayfalar yüklendiğinde dur
            } else {
                loadArticle(count); // Yeni sayfayı yükle
            }
            count++;
        }
    });

    function loadArticle(pageNumber) {
        $('a#inifiniteLoader').show('fast'); // Yükleme simgesini göster
        $.ajax({
            url: "<?php echo admin_url(); ?>admin-ajax.php",
            type: 'POST',
            data: "action=infinite_scroll&page_no=" + pageNumber + '&loop_file=loop',
            success: function(html) {
                $('li#inifiniteLoader').hide('1000'); // Yükleme simgesini gizle
                $("ul.timeline").append(html); // Yeni yazıları ekle
            }
        });
        return false;
    }
});
</script>

Customization for Category Pages

To load the correct posts on category pages (category.php), add the what and value parameters. For example:

<script type="text/javascript">
jQuery(document).ready(function($) {
    var count = 2;
    var total = <?php echo $wp_query->max_num_pages; ?>;
    $(window).scroll(function() {
        if ($(window).scrollTop() == $(document).height() - $(window).height()) {
            if (count > total) {
                return false;
            } else {
                loadArticle(count);
            }
            count++;
        }
    });

    function loadArticle(pageNumber) {
        $('a#inifiniteLoader').show('fast');
        $.ajax({
            url: "<?php echo admin_url(); ?>admin-ajax.php",
            type: 'POST',
            data: "action=infinite_scroll&page_no=" + pageNumber + '&loop_file=loop&what=category_name&value=<?php echo $yourcat->slug; ?>',
            success: function(html) {
                $('li#inifiniteLoader').hide('1000');
                $("ul.timeline").append(html);
            }
        });
        return false;
    }
});
</script>

Explanation of the Code

  • count: Determines which page to load. On the first load, it starts from page 2 because page 1 is already loaded.
  • total: Gets the total number of pages with WordPress's $wp_query->max_num_pages.
  • scroll eventWhen the user reaches the end of the page, an AJAX request is sent.
  • loadArticle: Shows the loading icon, pulls new posts with AJAX and adds them to the HTML.
  • what and value: Used to load the correct content on category or author pages. For example, value carries the category slug.

When I implemented this method on a blog site, only relevant posts were loaded on category pages, and users had an uninterrupted experience.

Conclusion

Adding infinite scrolling to your WordPress theme without a plugin is both performance-friendly and customizable. By following these steps, you can create seamless infinite scrolling on pages like index.php, category.php, or author.php. I've used this method in my own projects to improve the user experience and reduce plugin dependency. You too can give your site a modern touch by trying these codes!

4 3 votes
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

4 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Subhasish Nath

if I write the javascript in archive-posttype.php page, Will this code work for custom post type archive page?

Chris Najman

Hello Erhan. I'm afraid I couldn't get it to work! I set up a test site using the default theme (WordPress Twentyseventeen) and generated a set of posts, categories and tags (using FakerPress). I copied the loop from index.php to a file called loop.php and placed it in the root of the theme directory. I added the script to the bottom of both index.php and archive.php (Twentyseventeen theme uses this for archives, categories and tags). I added the function wp_infinitepaginate() to functions.php. Nothing happened at all and there were no errors in the console. Maybe I've misunderstood and I should… Read more »