infinitescroll php,WordPress: 增加无限分页(Infinite Scroll)功能

Infinite Scroll是一种动态加载内容的方式,当网页滚动到底部时,自动载入本需要翻页才能看到的内容,在社交应用中很常见,例如新浪微博。

WordPress.com已经支持了这个功能,但自己host的WordPress需要通过插件或代码添加,先介绍一下插件方法。

JetPack

如果你使用Jetpack by WordPress.com插件,那只需要一段简单的代码就可以开启infinite scroll功能,jetpack已经集成了该功能。

Infinite Scroll

直接安装Infinite-Scroll WordPress插件,如果你使用默认主题或一些知名主题,只要开启该插件就可以获得infinite scroll功能。如果是自己写的主题,就需要设置一番,完全不懂HTML的话可能会有些困难,需要设置的内容在第三节中将会提到。

不使用插件

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

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

3. 注册并加载infinite scroll所需要的脚本,将下面代码放在主题的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() ) {

?>

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 );

});

}

}

add_action('wp_footer', 'custom_infinite_scroll_js', 100);

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

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

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

下载源代码

这是一个带有infinite scroll功能的twentytwelve child theme,有需要的朋友请下载。

[download id=49]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值