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

Author: 陌小雨Date: 2024-12-20View: 236

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(); ?>
            

我们需要在前端发起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(); ?> 
                

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) : ?>

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

付费可见

已有0人支付

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