WordPress 添加 Infinite Scroll 无限分页功能

什么是 Infinite Scroll?Infinite Scroll是一种动态加载内容的方式,当网页滚动到底部时,自动载入本需要翻页才能看到的内容。目前 WordPress 已经支持这个 Infinite Scroll 功能,下面教大家如何添加:

1. 下载「infinite scroll」的zip压缩包,在根目录下找到jquery.infinitescroll.min.js这个文件,放到主题的js目录下。

2. 挑一张「ajax loader」图片作为loading时显示的图片,放到主题的images目录下。

3. 注册并加载infinite scroll所需要的脚本,将下面代码放在主题的functions.php中

后台」→「外观」→「编辑」→ 「functions.php」文件,把下面的代码添加进去:

/**
 * Load javascripts used by the theme
 */
function custom_theme_js() {
    wp_register_script('infinite_scroll', get_stylesheet_directory_uri() . '/js/jquery.infinitescroll.min.js', array('jquery'), null, true);
    if (!is_singular()) {
        wp_enqueue_script('infinite_scroll');
    }
}
 
add_action('wp_enqueue_scripts', 'custom_theme_js');

4. 初始化infinite scroll,这里需要你懂HTML了,这里我们要找一些相关的css selector,才能继续完成代码。

  • img: ajax loader gif图片的url
  • nextSelector: 能够选中下一页(Previous Post)链接元素的css selector
  • navSelector: 包含上一页/下一页链接的元素的css selector
  • itemSelector: 包含每篇post内容的元素的css selector
  • contentSelector: 包含所有文章的container元素的css selector
/**
 * Infinite Scroll
 */
function custom_infinite_scroll_js() {
    if (!is_singular() ) {
        ?>
        <script type="text/javascript">
        jQuery(document).ready(function(){
            /**
             * Customize the previous navitation menu
             */         
            var infinite_scroll = {
                loading: {
                    img: "<?php echo get_stylesheet_directory_uri(); ?>/images/ajax-loader.gif",
                    msgText: "<?php _e('Loading the next set of posts...', 'tt_child'); ?>",
                    finishedMsg: "<?php _e('All posts loaded.', 'tt_child'); ?>"
                },
                nextSelector:"#nav-below .nav-previous a",
                navSelector:"#nav-below",
                itemSelector:"article",
                contentSelector:"#content"
            };
            jQuery( infinite_scroll.contentSelector ).infinitescroll( infinite_scroll );
        });
        </script>
        <?php
    }
}
 
add_action('wp_footer', 'custom_infinite_scroll_js', 100);

如果使用Infinite Scroll插件时总是出错,多半是这几个selector没找对,只有找对这些class才能让代码工作。

注意:上述代码使用get_stylesheet_directory_uri获取路径,如果你需要的资源在parent theme中,请替换成get_template_directory_uri。

现在一切都准备好了,到前台刷新一下页面,滚动页面,当滚动到底部时,应该会自动加载更多文章,加载文章的数量取决于后台设置->阅读中的“博客页面至多显示”选项的值。

# 更多WordPress技巧,请关注「WordPress专题

方法来源:solagirl