You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

集成ACF粘性文章后Ajax筛选与加载更多功能异常求助

解决ACF粘性文章+Ajax加载更多+筛选的异常问题

问题概述

  • 点击加载更多时,粘性文章重复出现,分页逻辑错乱
  • 选择筛选器“全部”选项时,文章无法重置为初始状态

解决方案

1. 修复后端Ajax函数核心问题

问题根源:

  • else if ($projects_category = 'all') 是赋值操作而非比较,导致逻辑错误
  • 加载更多时重复输出粘性文章
  • 分页总数错误使用了粘性文章查询的max_num_pages

修改后的Ajax函数代码:

add_action('wp_ajax_nopriv_filter_project', 'filter_project');
add_action('wp_ajax_filter_project', 'filter_project');

function filter_project()
{
    $projects_category = isset($_POST['projects_category']) ? $_POST['projects_category'] : 'all';
    $ids = get_field('sticky_projects', false, false);
    // 处理空粘性ID数组,避免WP_Query报错
    if (empty($ids)) $ids = [0];
    $meta_query = [];
    $paged = (int) $_POST['paged'];
    $posts_per_page = isset($_POST['posts_per_page']) ? (int)$_POST['posts_per_page'] : 4;

    if ($projects_category != 'all') {
        $meta_query[] = [
            'key' => 'projects_category',
            'value' => $projects_category,
            'compare' => 'LIKE'
        ];

        $args = array(
            'post_type' => 'cpt_projects',
            'post_status' => 'publish',
            'meta_query' => $meta_query,
            'orderby' => 'date',
            'order'   => 'DESC',
            'posts_per_page' => $posts_per_page,
            'paged' => $paged,
            'post__not_in' => $ids, // 筛选时排除粘性文章,避免重复
        );

        $query = new WP_Query($args);

        if ($query->have_posts()) :
            while ($query->have_posts()) : $query->the_post();
                project::render();
            endwhile;
            echo '<input type="hidden" name="number_pages" value="' . $query->max_num_pages . '" id="project_number_pages" />';
        endif;

        wp_reset_postdata();
    } else {
        // 仅第一页输出粘性文章
        if ($paged === 1) {
            $sticky_query = new WP_Query(array(
                'post_type' => 'cpt_projects',
                'post__in' => $ids,
                'post_status' => 'publish',
            ));

            while ($sticky_query->have_posts()) : $sticky_query->the_post();
                project::render();
            endwhile;
            wp_reset_postdata();
        }

        // 非粘性文章的分页查询
        $regular_args = array(
            'post_type' => 'cpt_projects',
            'post__not_in' => $ids,
            'post_status' => 'publish',
            'posts_per_page' => $posts_per_page,
            'paged' => $paged,
            'orderby' => 'date',
            'order'   => 'DESC',
        );

        $regular_query = new WP_Query($regular_args);

        while ($regular_query->have_posts()) : $regular_query->the_post();
            project::render();
        endwhile;
        // 分页总数使用非粘性文章的查询结果
        echo '<input type="hidden" name="number_pages" value="' . $regular_query->max_num_pages . '" id="project_number_pages" />';

        wp_reset_postdata();
    }

    die();
}

2. 修正初始模板的分页总数问题

原模板中错误使用粘性文章查询的分页数,改为非粘性文章的分页数据:

<?php echo '<input type="hidden" name="number_pages" value="' . $query2->max_num_pages . '" id="project_number_pages" />'; ?>

3. 优化前端脚本逻辑

问题根源:

  • 初始totalpages获取为空时导致加载更多判断错误
  • 筛选“全部”时未正确重置页码和按钮状态

修改后的前端脚本:

$('#filter-form').on('click', 'input', function (e) {
    $(this).parents('li').siblings().removeClass('active')
    $(this).parents('li').toggleClass('active');
    filter_form();
});

$('body').on('click', 'a.load-more', function (e) {
    filter_form(true);
});

function filter_form(next_page = false) {
    var page = $('#js-filter').data('page') || 1;
    var totalpages = $('#project_number_pages').val() || 1;

    if (next_page) {
        page += 1;
    } else {
        page = 1;
        $('a.load-more').show(); // 重置筛选时显示加载更多按钮
    }
    $('#js-filter').data('page', page);

    console.log('Page is ' + page + ' total pages is ' + totalpages);
    // 处理总页数为0的边界情况
    if (totalpages > 0 && page >= totalpages) {
        $('a.load-more').hide();
    } else {
        $('a.load-more').show();
    }

    var projects_category = $('input[name="projects_category"]:checked').val() || 'all';
    var ajax_data = {
        projects_category: projects_category,
        action: 'filter_project',
        nonce: winc.nonce,
        posts_per_page: 4,
        paged: page
    };

    $.ajax({
        url: winc.ajaxurl,
        data: ajax_data,
        type: 'post',
        success: function (response) {
            if (next_page) {
                $('#js-filter').append(response);
            } else {
                $('#js-filter').html(response);
            }
            // 更新总页数,确保后续加载更多判断准确
            totalpages = $('#project_number_pages').val() || 1;
            if (totalpages > 0 && page >= totalpages) {
                $('a.load-more').hide();
            }
        },
        error: function (response) {
            console.warn(response);
        },
    });
}

关键修改说明

  • 后端:
    1. 修正$projects_category = 'all'的赋值错误,改为比较判断
    2. 仅在第一页输出粘性文章,避免加载更多重复显示
    3. 分页总数使用非粘性文章查询的max_num_pages,确保分页逻辑正确
    4. 筛选非“全部”选项时自动排除粘性文章,避免重复
  • 前端:
    1. 优化页码和总页数的默认值处理,避免空值导致逻辑错误
    2. 重置筛选时强制显示加载更多按钮,保证状态正确
    3. Ajax成功后重新获取总页数,确保后续加载更多判断准确
  • 初始模板:修正分页总数的查询对象,使用非粘性文章的分页数据

内容的提问来源于stack exchange,提问作者Paddy Winsley

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 14:44:58