wordpress ajax 分页实现方法

作者:袖梨 2022-06-25

由于我们可以在后台使用wp query来输出文章列表,所以我们并不需要文章分页的入口,砍掉了分页入口也避免了搜索引擎抓取这些页面。我们只需要在AJAX 执行的过程中向后台传递一个分页参数,就可以返回这个分页上的文章列表。再返回文章列表的时候,我们还需要返回下一分页的页码,当然如果不是最后一页的话。

鉴于wp query有着丰富的参数,我们可以通过转递指定的参数来控制文章列表的输出,使之可以在分类、标签等归档正常使用。

实现方法
例如你的index.php的代码是如下结构

<?php get_header();?>
   
        //注意这个class,需要和下面的匹配
            <?php if (have_posts()):
                while (have_posts()): the_post();
                    get_template_part('content', 'list');
                endwhile;
            endif;?>
       
       
            <?php echo fa_load_postlist_button();?>//加载更多按钮 
       
   
<?php get_footer();?>
content-list.php文章结构


   


        <?php the_title();?>
   


   
   

        <?php if(has_post_thumbnail()):?>
           

<?php the_post_thumbnail( 'full' ); ?>


           

<?php echo mb_strimwidth(strip_shortcodes(strip_tags(apply_filters('the_content', $post->post_content))), 0, 220,"...");?>


        <?php else : ?>
        <?php the_content('');?>   
        <?php endif;?>
   

   

把下面的代码加入functions.php

function fa_load_postlist_button(){//这是加载更多按钮
    global $wp_query;
    if (2 > $GLOBALS["wp_query"]->max_num_pages) {
        return;
    } else {
        $button = '         if (is_category()) $button .= ' data-category="' . get_query_var('cat') . '"';
        if (is_author()) $button .=  ' data-author="' . get_query_var('author') . '"';
        if (is_tag()) $button .=  ' data-tag="' . get_query_var('tag') . '"';
        if (is_search()) $button .=  ' data-search="' . get_query_var('s') . '"';
        if (is_date() ) $button .=  ' data-year="' . get_query_var('year') . '" data-month="' . get_query_var('monthnum') . '" data-day="' . get_query_var('day') . '"';
        $button .= ' data-paged="2" data-action="fa_load_postlist" data-total="' . $GLOBALS["wp_query"]->max_num_pages . '">加载更多';
        return $button;
    }
}
function puma_post_section(){//这就是点击加载更多按钮时会刷出来的文章结构,建议和content-list.php的结构保持一致。
    global $post;
    $post_section = '

' . get_the_title() . '


   
   
';
    if(has_post_thumbnail()) {
        $post_section .= '

' . get_the_post_thumbnail() . '

' . mb_strimwidth(strip_shortcodes(strip_tags(apply_filters('the_content', $post->post_content))), 0, 220,"...") . '

';
    } else {
        $post_section .= apply_filters('the_content', get_the_content(''));
    }
    $post_section .= '

    ';
    return $post_section;
}
add_action('wp_ajax_nopriv_fa_load_postlist', 'fa_load_postlist_callback');
add_action('wp_ajax_fa_load_postlist', 'fa_load_postlist_callback');
function fa_load_postlist_callback(){
    $postlist = '';
    $paged = $_POST["paged"];
    $total = $_POST["total"];
    $category = $_POST["category"];
    $author = $_POST["author"];
    $tag = $_POST["tag"];
    $search = $_POST["search"];
    $year = $_POST["year"];
    $month = $_POST["month"];
    $day = $_POST["day"];
    $query_args = array(
        "posts_per_page" => get_option('posts_per_page'),
        "cat" => $category,
        "tag" => $tag,
        "author" => $author,
        "post_status" => "publish",
        "post_type" => "post",
        "paged" => $paged,
        "s" => $search,
        "year" => $year,
        "monthnum" => $month,
        "day" => $day
    );
    $the_query = new WP_Query( $query_args );
    while ( $the_query->have_posts() ){
        $the_query->the_post();
        $postlist .= puma_post_section();
    }
    $code = $postlist ? 200 : 500;
    wp_reset_postdata();
    $next = ( $total > $paged )  ? ( $paged + 1 ) : '' ;
    echo json_encode(array('code'=>$code,'postlist'=>$postlist,'next'=> $next));
    die;
}
剩下的就是加载js代码了,需要加载jquery库,方法就不说了。
jQuery(document).on("click", "#fa-loadmore", function() {
 var _self = jQuery(this),
  _postlistWrap = jQuery('.blockGroup'),
  _button = jQuery('#fa-loadmore'),
  _data = _self.data();
 if (_self.hasClass('is-loading')) {
  return false
 } else {
  _button.html('加载中 o(∩_∩)o');
  _self.addClass('is-loading');
  jQuery.ajax({
   url: '/wp-admin/admin-ajax.php',//注意该文件路径
   data: _data,
   type: 'post',
   dataType: 'json',
   success: function(data) {
    if (data.code == 500) {
     _button.data("paged", data.next).html('加载更多');
     alert('服务器正在努力找回自我  o(∩_∩)o')
    } else if (data.code == 200) {
     _postlistWrap.append(data.postlist);
     if (data.next) {
      _button.data("paged", data.next).html('加载更多')
     } else {
      _button.remove()
     }
    }
    _self.removeClass('is-loading')
   }
  })
 }
});
本功能可完美用户各个文章列表,如果你添加了自定义文章类型则代码需要相应修改

相关文章

精彩推荐