在WordPress上添加无限滚动功能需要用到jQuery插件,可以选择使用Infinite Scroll插件。首先,在 WordPress 的主题文件中添加下面这个代码块到 functions.php 文件中:
function my_infinite_scroll_scripts() {
wp_enqueue_script( 'infinite-scroll', get_template_directory_uri() . '/js/jquery.infinitescroll.min.js', array( 'jquery' ), '3.0.2', true );
}
add_action( 'wp_enqueue_scripts', 'my_infinite_scroll_scripts' );
上述代码添加了infinitescroll.min.js脚本,这是无限滚动插件的核心文件。
接下来是实现代码。在主题的JavaScript文件中添加以下代码:
jQuery(document).ready(function($) {
$('.masonry-style').imagesLoaded(function(){
$('.masonry-style').infinitescroll({
navSelector: "#next-page", // 你下一页的链接的class
nextSelector: "#next-page a", // 下一页链接中的的链接
itemSelector: ".grid", // 要加载新内容的选择器
loading: {
finishedMsg: '',
msgText: "<em>加载中...</em>",
img: "<?php echo get_template_directory_uri(); ?>/images/loading.gif"
},
errorCallback: function(){
$('#infscr-loading').remove();
$('#infscr-loading-b').remove();
}
});
$('.masonry-style').on('before-append', function(){
$('.masonry-style').masonry('reloadItems');
$('.masonry-style').masonry('layout');
});
});
});
以上代码需要根据实际情况进行调整,其中需要注意的是:
最后,根据你的主题不同,可能需要在CSS文件中添加以下代码
#infscr-loading {
background: none;
text-align: center;
font-size: 14px;
color: #666;
margin-top: 20px;
}
通过以上步骤即可为你的 WordPress 主题添加无限滚动功能。