微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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中文社区问答版块儿进行提问,我们会在第一时间给大家回复,希望以上内容能够帮助到您。

 

 

 

 

 

原文地址:https://www.jb51.cc/wordpress/4741903.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐