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、把下面的代码放到你前端需要显示文章列表的地方

<ul class="jubenlists">

<?php

$args = array(

'post_type' => 'post',

);

$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方法中循环体要和你前端列表中默认显示出来的几条列表中的循环体一致,而且要注意相关标点符号的使用。

具体的使用过程中有什么问题大家可以到WordPress中文社区问答版块儿进行提问,我们会在第一时间给大家回复,希望以上内容能够帮助到您。

相关文章

我想将wordpress的默认接口路由改掉,愿意是默认的带一个 wp...
wordpress自定义分类法之后,我看到链接都自动在后面添加了一...
事情是这样的,我用 get_post_type 函数创建了一个自定义分类...
最近网站莫名其妙的被顶上了,过一个多小时,就注册一个账号...
最近服务器要到期了,就想着把网站转移到另外一台服务器,本...
今天在写wordpress的接口,然后碰到个奇怪的问题,怎么访问都...