admin管理员组

文章数量:1122846

Background information can be skipped.


I wanted to use the infinite scrolling option on my Wordpress theme, but I am not well trained in Javascript so I tried this solution:

/

function custom_infinite_scroll_js() {
    //Code as given in the link above
}
add_action( 'wp_footer', 'custom_infinite_scroll_js', 100 );

I wasted my couple of days at the above-mentioned article and later realized that everything is outdated and even the JS by metafizzy has been updated.

Challenges faced were:

img: The path to the ajax loader image
nextSelector: Selector for the “previous posts” link.
navSelector: Containing selector for the previous/next navigation links.
itemSelector: Selector for posts. This might be .hentry, .post, .etc
contentSelector: Containing div for your posts.
  1. Could not understand how to find these selectors in my theme.
  2. some bugs in V2

Decided to use V3 and move on to the lastest version of the infinite scroll

V2 has been updated to V3 The details can be found here.

.html#v2-upgrade-example

I created a function like this →

function custom_infinite_scroll_js() {
if ( ! is_singular() ) { ?>
<script>
    var $container = $('.container').infiniteScroll({
    append: '.post',
    path: '.pagination__next',
    status: '.page-load-status',
    });

    // use event for v2 callback
    $container.on( 'append.infiniteScroll', function( event, response, path, items ) {
    $( items ).tooltip();
    });
</script>
<?php
}
}
add_action( 'wp_footer', 'custom_infinite_scroll_js', 100 );

But it doesn't actually create an infinite scroll. Can someone guide me how to proceed.

Background information can be skipped.


I wanted to use the infinite scrolling option on my Wordpress theme, but I am not well trained in Javascript so I tried this solution:

https://wptheming.com/2012/03/infinite-scroll-to-wordpress-theme/

function custom_infinite_scroll_js() {
    //Code as given in the link above
}
add_action( 'wp_footer', 'custom_infinite_scroll_js', 100 );

I wasted my couple of days at the above-mentioned article and later realized that everything is outdated and even the JS by metafizzy has been updated.

Challenges faced were:

img: The path to the ajax loader image
nextSelector: Selector for the “previous posts” link.
navSelector: Containing selector for the previous/next navigation links.
itemSelector: Selector for posts. This might be .hentry, .post, .etc
contentSelector: Containing div for your posts.
  1. Could not understand how to find these selectors in my theme.
  2. some bugs in V2

Decided to use V3 and move on to the lastest version of the infinite scroll

V2 has been updated to V3 The details can be found here.

https://infinite-scroll.com/extras.html#v2-upgrade-example

I created a function like this →

function custom_infinite_scroll_js() {
if ( ! is_singular() ) { ?>
<script>
    var $container = $('.container').infiniteScroll({
    append: '.post',
    path: '.pagination__next',
    status: '.page-load-status',
    });

    // use event for v2 callback
    $container.on( 'append.infiniteScroll', function( event, response, path, items ) {
    $( items ).tooltip();
    });
</script>
<?php
}
}
add_action( 'wp_footer', 'custom_infinite_scroll_js', 100 );

But it doesn't actually create an infinite scroll. Can someone guide me how to proceed.

Share Improve this question edited Jun 15, 2020 at 8:21 CommunityBot 1 asked Feb 3, 2018 at 2:52 WordCentWordCent 1,8775 gold badges34 silver badges60 bronze badges 1
  • @David Sword, I have accepted the edit can you please suggest a working solution? – WordCent Commented Feb 3, 2018 at 5:10
Add a comment  | 

2 Answers 2

Reset to default 3

For single article infinite scroll below is the solution

single.php

<div class="blog-article-section"> 
<?php while( have_posts() ): ?>   
<div class="blog-article">
  <?php if( have_posts() ): the_post(); ?>
    <h2><?php the_title(); ?></h2>
    <p><?php the_content(); ?></p>
  <?php endif;  ?>
  <div class="pagination-single" >
    <div class="next_post_link"><?php previous_post_link( '%link','Previous Post' ) ?></div>
    <div class="previous_post_link"><?php next_post_link( '%link','Next Post' ) ?></div>
  </div>
</div>
<?php endwhile; ?>
</div>
<div class="blog-article1"></div>
<a href="#" class="loadArticle">Load more</a>

script.js

(function($) {
$(document).ready(function(){
    var next_count = 1;
    $('.next_post_link a').attr("id", "next"+next_count);
    var prev_count = 1;
    $('.prev_post_link a').attr("id", "prev"+prev_count);
    $(".loadArticle").click(function(e) {
        e.preventDefault();
        loadNextArticle();
    });
    $(window).scroll(function(){
        loadNextArticle();
        console.log('scroll')
    });
    function loadNextArticle(){
        var next_link = $("#next"+next_count).attr("href");
        var prev_link = $("#prev"+prev_count).attr("href");
         if(typeof(next_link) != "undefined"){
            $.ajax({
              type: "GET",
              url: next_link,
              data: {},
              async: false,
              success: function(data){
                next_count = ++next_count;
                var result = $(data);
                $('.next_post_link a', result).attr("id","next"+next_count);
                result.find('.blog-article').appendTo('.blog-article1').fadeIn('slow');
              }
            });
        } 
    }
});
}(jQuery));

To implement infinite scroll in WordPress, you can use various methods, including JavaScript with the WordPress REST API or a library like jQuery. Below is a step-by-step guide to implementing infinite scroll using JavaScript and the WordPress REST API.

Step 1: Enqueue Scripts

First, enqueue your JavaScript file in your theme’s functions.php file.

function enqueue_infinite_scroll_script() {
    wp_enqueue_script(
        'infinite-scroll',
        get_template_directory_uri() . '/js/infinite-scroll.js',
        array('jquery'),
        null,
        true
    );

    // Localize script to pass data to JavaScript
    wp_localize_script(
        'infinite-scroll',
        'infinite_scroll_params',
        array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'query_vars' => json_encode($wp_query->query),
        )
    );
}
add_action('wp_enqueue_scripts', 'enqueue_infinite_scroll_script');

Step 2: Create JavaScript File

Create a js/infinite-scroll.js file in your theme directory. This file will handle the AJAX request to load more posts.

jQuery(function($) {
    var canBeLoaded = true, // this param allows to initiate the AJAX call only if necessary
        bottomOffset = 2000; // the distance (in px) from the page bottom when you want to load more posts

    $(window).scroll(function() {
        var data = {
            'action': 'loadmore',
            'query': infinite_scroll_params.query_vars, // that's how we get params from wp_localize_script() function
            'page': infinite_scroll_params.current_page
        };

        if ($(document).scrollTop() > ($(document).height() - bottomOffset) && canBeLoaded == true) {
            $.ajax({
                url: infinite_scroll_params.ajax_url,
                data: data,
                type: 'POST',
                beforeSend: function(xhr) {
                    canBeLoaded = false; // disable the ajax call while it's in progress
                },
                success: function(data) {
                    if (data) {
                        $('#content').find('article:last-of-type').after(data); // insert new posts
                        infinite_scroll_params.current_page++;
                        canBeLoaded = true; // the ajax call is complete, now we can allow it again
                    }
                }
            });
        }
    });
});

Step 3: Handle AJAX Request

In your theme’s functions.php file, add a function to handle the AJAX request and return the posts.

function loadmore_ajax_handler() {
    // Prepare our arguments for the query
    $args = json_decode(stripslashes($_POST['query']), true);
    $args['paged'] = $_POST['page'] + 1; // we need next page to be loaded
    $args['post_status'] = 'publish';

    // Query posts
    query_posts($args);

    if (have_posts()) :
        // Start the loop
        while (have_posts()): the_post();

            // Your content here
            get_template_part('template-parts/content', get_post_format());

        endwhile;
    endif;
    die; // here we exit the script and even no wp_reset_query() required!
}

add_action('wp_ajax_loadmore', 'loadmore_ajax_handler'); // if called from admin panel
add_action('wp_ajax_nopriv_loadmore', 'loadmore_ajax_handler'); // if called from elsewhere

Step 4: Modify the Query

Modify your main query to pass necessary parameters to JavaScript.

global $wp_query;
wp_localize_script('infinite-scroll', 'infinite_scroll_params', array(
    'ajax_url' => admin_url('admin-ajax.php'),
    'query_vars' => json_encode($wp_query->query),
    'current_page' => get_query_var('paged') ? get_query_var('paged') : 1,
));

Step 5: Add Infinite Scroll Styles (Optional)

You might want to add some styles for the loading indicator or other elements related to infinite scroll.

/* Example CSS for the loading indicator */
.loading {
    text-align: center;
    padding: 20px;
    display: none;
}

.loading img {
    width: 32px;
    height: 32px;
}

Summary

With these steps, you will have implemented infinite scroll on your WordPress site. Adjust the code as needed to fit your theme's structure and design.

本文标签: phpWordpress Infinite Scroll without using any plugin