wordpress短代码实现分类文章ajax筛选

Author: 陌小雨Date: 2020-09-02View: 147

ajax是wordpress中比较常用的功能,下面小雨实战分享如何通过短代码的方式进行分类文章的筛选

首先是创建一个短代码,短代码的好处是可以复用,不需要一大片一大片重复的代码

add_shortcode( 'wpsite_posts', 'wpsite_ajax_posts_filter');
function wpsite_ajax_posts_filter($atts) {
    $a = shortcode_atts( array(
        'tax'      => 'category', //可以改为post_tag
        'terms'    => false, //排除某个分类
        'active'   => false, //设定默认加载哪个分类
        'per_page' => 12 //设定每页文章数量
    ), $atts );
    $result = NULL;
    $terms  = get_terms($a['tax']);
   //排除某个分类就用下面一句,在短码添加terms='分类id'就可以排除
   //$terms = get_terms($a['tax'],array('exclude' =>$a['terms'])); 
    if (count($terms)) :
        ob_start(); ?>
            <div id="container-async" data-paged="<?php echo $a['per_page']; ?>" class="sc-ajax-filter">
                <ul class="nav-filter">
		<li><a href="#" data-filter="post_tag" data-term="all-terms" data-page="1">所有</a></li>
                    <?php foreach ($terms as $term) : ?>
                        <li<?php if ($term->term_id == $a['active']) :?> class="active"<?php endif; ?>>
                            <a href="<?php echo get_term_link( $term, $term->taxonomy ); ?>" data-filter="<?php echo $term->taxonomy; ?>" data-term="<?php echo $term->slug; ?>" data-page="1">
                                <?php echo $term->name; ?>
                            </a>
                        </li>
                    <?php endforeach; ?>
                </ul> 
                <div class="status"></div>
                <div class="content"></div>
            </div> 
        <?php $result = ob_get_clean();
    endif;
    return $result;
}

我们需要在前端发起ajax请求,建立一个main.js

$('#container-async').on('click', 'a[data-filter], .pagination a', function(event) {
            if(event.preventDefault) { event.preventDefault(); } 
            $this = $(this);
            if ($this.data('filter')) {
                $this.closest('ul').find('.active').removeClass('active');
                $this.parent('li').addClass('active');
                $page = $this.data('page');
            }
            else {
                $page = parseInt($this.attr('href').replace(/\D/g,''));
                $this = $('.nav-filter .active a');
            }
            $params    = {
                'page' : $page,
                'tax'  : $this.data('filter'),
                'term' : $this.data('term'),
                'qty'  : $this.closest('#container-async').data('paged'),
            };
            wpsite_get_posts($params);
        });
 
        $('a[data-term="all-terms"]').trigger('click');

        function wpsite_get_posts($params) { 
            $container = $('#container-async');
            $content   = $container.find('.content');
            $status    = $container.find('.status'); 
            $status.text('正在加载 ...'); 
            $.ajax({
                        url: jsonvue.ajax_url,
                        data: {
                            action: 'wpsite_filter_posts',
                            nonce: jsonvue.nonce,
                            params: $params
                        },
                        type: 'post',
                        dataType: 'json',
                        success: function(data, textStatus, XMLHttpRequest) { 
                            if (data.status === 200) {
                                $content.html(data.content);
                            }
                            else if (data.status === 201) {
                                $content.html(data.message);    
                            }
                            else {
                                $status.html(data.message);
                            }
                     },
                    error: function(MLHttpRequest, textStatus, errorThrown) { 
                        $status.html(textStatus); 
                        /*console.log(MLHttpRequest);
                        console.log(textStatus);
                        console.log(errorThrown);*/
                     },
                    complete: function(data, textStatus) { 
                        msg = textStatus; 
                        if (textStatus === 'success') {
                            msg = data.responseJSON.found;
                         } 
                        $status.text('已显示: ' + msg+'篇文章'); 
                        /*console.log(data);
                        console.log(textStatus);*/
                }
            });
        }

接着就是php部分了

function wpsite_filter_posts() {
    if( !isset( $_POST['nonce'] ) || !wp_verify_nonce( $_POST['nonce'], 'jsonvue' ) )
        die('Permission denied'); 
    $response = [
        'status'  => 500,
        'message' => '貌似有错误,请稍后再试 ...',
        'content' => false,
        'found'   => 0
    ];
    $tax  = sanitize_text_field($_POST['params']['tax']);
    $term = sanitize_text_field($_POST['params']['term']);
    $page = intval($_POST['params']['page']);
    $qty  = intval($_POST['params']['qty']);
 
    if (!term_exists( $term, $tax) && $term != 'all-terms') :
        $response = [
            'status'  => 501,
            'message' => '没找到分类',
            'content' => 0
        ];
        die(json_encode($response));
    endif;
    if ($term == 'all-terms') : 
        $tax_qry[] = [
            'taxonomy' => $tax,
            'field'    => 'slug',
            'terms'    => $term,
            'operator' => 'NOT IN'
        ];
    else :
        $tax_qry[] = [
            'taxonomy' => $tax,
            'field'    => 'slug',
            'terms'    => $term,
        ];
    endif; 
    $args = [
        'paged'          => $page,
        'post_type'      => 'post',
        'post_status'    => 'publish',
        'posts_per_page' => $qty,
        'tax_query'      => $tax_qry
    ];
    $qry = new WP_Query($args);
    ob_start();
        if ($qry->have_posts()) :
            while ($qry->have_posts()) : $qry->the_post(); ?> 
                <article class="loop-item">
                    <header>
                        <h2 class="entry-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
                    </header>
                    <div class="entry-summary">
                        <?php the_excerpt(); ?>
                    </div>
                </article> 
            <?php endwhile;
            wpsite_ajax_pager($qry,$page);
            $response = [
                'status'=> 200,
                'found' => $qry->found_posts
            ];
        else :
            $response = [
                'status'  => 201,
                'message' => '没有文章'
            ];
        endif;
    $response['content'] = ob_get_clean();
    die(json_encode($response));
}
add_action('wp_ajax_do_filter_posts', 'jsonvue_filter_posts');
add_action('wp_ajax_nopriv_do_filter_posts', 'jsonvue_filter_posts');

function wpsite_ajax_pager( $query = null, $paged = 1 ) {
    if (!$query)
        return;
    $paginate = paginate_links([
        'base'      => '%_%',
        'type'      => 'array',
        'total'     => $query->max_num_pages,
        'format'    => '#page=%#%',
        'current'   => max( 1, $paged ),
        'prev_text' => 'Prev',
        'next_text' => 'Next'
    ]);
    if ($query->max_num_pages > 1) : ?>
        <ul class="pagination">
            <?php foreach ( $paginate as $page ) :?>
                <li><?php echo $page; ?></li>
            <?php endforeach; ?>
        </ul>
    <?php endif;
}

最后加载必须的js和自定义的变量即可

付费可见

已有0人支付

好了,一个浩浩荡荡的wordpress短代码实现分类文章ajax筛选功能就完成了,赶快试试吧!