Ajax实现WordPress移动文章列表页面无限下拉加载
在定制WordPress主题时,由于这个主题主要是面向移动端的,使用文章列表页面上的页面不是很友好,所以我选择了使用无限下拉加载方式。现将具体实现分享给大家。
1。将下面定义的ajax下载文章的内容放入您的functions.php
//ajax加载文章列表
add_action('wp_ajax_nopriv_ajax_index_post', 'ajax_index_post');
add_action('wp_ajax_ajax_index_post', 'ajax_index_post');
function ajax_index_post(){
$paged = $_POST["paged"];
$total = $_POST["total"];
$args = array(
'post_type' => 'post',
'posts_per_page'=>get_option('posts_per_page'),
'paged' => $paged,
'orderby' => 'date',
);
$the_query = new WP_Query($args);
while ( $the_query->have_posts() ){
$the_query->the_post();
echo
'<li><a href="'.get_the_permalink().'" title="'.get_the_title().'">"'.get_the_title().'"</a></li>';
}
wp_reset_postdata();
if ( $total > $paged ) echo '<a id="show-more" href="javascript:;" data-total="'.$total.'" data-paged = "'.($paged+1).'" class="show-more m-feed–loader">上拉加载更多</a>';
die();
}
2中。下面是下面定义的下载按钮(文本提示)函数,也将其放入functions.php文件中
//ajax无限加载文章列表按钮
function ajax_show_more_button(){
if( 2 > $GLOBALS["wp_query"]->max_num_pages){
return;
}
echo '<a id="show-more" href="javascript:;" data-paged = "2" data-total="'.$GLOBALS["wp_query"]->max_num_pages.'" class="show-more m-feed–loader">上拉加载更多</a>';
}
3. 将以下代码放入UI中要显示文章列表的位置
<ul class="jubenlists">
<?php
$args = array(
'post_type' => 'post',
'posts_per_page'=>get_option('posts_per_page'),
'orderby' => 'date',
);
$args['tax_query'] = array();
query_posts($args);?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<li>
<a href="<?php%20the_permalink();?>" title="<?php the_title();?>">
<?php the_title();?>
</a>
</li>
<?php endwhile; else: ?>
<p class="nojuben">没有找到相关内容</p>
<?php endif; ?>
<?php ajax_show_more_button();?>//这里就是主要的地方,正常的分页这里是用的分页函数,而我们需要使用的是定义的ajax函数
</ul>
4。 js 文件
<script type="text/javascript">
var H = false;
jQuery(window).scroll(function(i) {
if (jQuery("#show-more").length > 0) {
var q = jQuery(window).scrollTop(),
p = jQuery("#show-more").offset().top,
$this = jQuery("#show-more");
if (q + jQuery(window).height() >= p && H != true) {
var paged = $this.data("paged"),
total = $this.data("total");
var ajax_data = {
action: "ajax_index_post",
paged: paged,
total: total
};
H = true;
$this.html('加载中…').addClass('is-loading')
jQuery.post('/wp-admin/admin-ajax.php', ajax_data,
function(data) {
jQuery('#show-more').remove();
H = false;
jQuery(".jubenlists").append(data);//这里是包裹文章的容器名
});
return false;
}
}
})
</script>
使用上述方法和步骤完成文章列表无限下拉列表。当然,上面的循环体(即每篇文章中出现的内容)是比较简单的。我只是使用了一个带有联系的标题。你可以根据自己的需要修改循环体的结构,但是要注意第一篇文章中定义的ajax方法中的循环体。应与界面列表中默认显示的列表的循环部分保持一致,并注意相关标点符号的使用。
版权声明
本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。