北极寒流 » 网络资源 » wordpress ajax 翻页实现方法 - 2015.11.24

wordpress ajax 翻页实现方法

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

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

实现方法

例如你的index.php的代码是如下结构

<?php get_header();?>
    <main class="main-content">
        <section class="blockGroup">//注意这个class,需要和下面的匹配
            <?php if (have_posts()):

                while (have_posts()): the_post();

                    get_template_part('content', 'list');

                endwhile;
            endif;?>
        </section>
        <nav class="posts-nav u-textAlignCenter">
            <?php echo fa_load_postlist_button();?>//加载更多按钮 
        </nav>
    </main>
<?php get_footer();?>

content-list.php文章结构

<article class="block block--inset block--list">
    <h2 class="block-title post-featured" itemprop="headline">
        <a href="<?php the_permalink();?>"><?php the_title();?></a>
    </h2>
    <div class="block-postMetaWrap u-textAlignCenter">
        <time><?php echo get_the_date('Y/m/d');?></time>
    </div>
    <div class="block-snippet block-snippet--subtitle grap" itemprop="about">
        <?php if(has_post_thumbnail()):?>
            <p class="with-img"><?php the_post_thumbnail( 'full' ); ?></p>
            <p><?php echo mb_strimwidth(strip_shortcodes(strip_tags(apply_filters('the_content', $post->post_content))), 0, 220,"...");?></p>
        <?php else : ?>
        <?php the_content('');?>   
        <?php endif;?>
    </div>
    <div class="block-footer">
        By <?php the_author();?> . In <?php the_category(',');?>.
    </div>
</article>

把下面的代码加入functions.php

function fa_load_postlist_button(){//这是加载更多按钮
    global $wp_query;
    if (2 > $GLOBALS["wp_query"]->max_num_pages) {
        return;
    } else {
        $button = '<button id="fa-loadmore" class="button button--primary"';
        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 . '">加载更多</button>';

        return $button;
    }
}

function puma_post_section(){//这就是点击加载更多按钮时会刷出来的文章结构,建议和content-list.php的结构保持一致。
    global $post;
    $post_section = '<article class="block block--inset block--list"><h2 class="block-title post-featured"><a href="' . get_permalink() . '">' . get_the_title() . '</a></h2>
    <div class="block-postMetaWrap u-textAlignCenter">
        <time>' . get_the_date('Y/m/d') . '</time>
    </div>
    <div class="block-snippet block-snippet--subtitle grap" itemprop="about">';

    if(has_post_thumbnail()) {
        $post_section .= '<p class="with-img">' . get_the_post_thumbnail() . '</p><p>' . mb_strimwidth(strip_shortcodes(strip_tags(apply_filters('the_content', $post->post_content))), 0, 220,"...") . '</p>';
    } else {
        $post_section .= apply_filters('the_content', get_the_content(''));
    }

    $post_section .= '</div>
    <div class="block-footer">
        By ' . get_the_author() .' . In ' . get_the_category_list(',') .'.';
    $post_section .= '</div></article>';
    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')
			}
		})
	}
});

本功能可完美用户各个文章列表,如果你添加了自定义文章类型则代码需要相应修改。

资料来源:https://fatesinger.com/76920

最受欢迎的