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

如何让WooCommerce Ajax加载更多与Ajax属性筛选兼容?

WooCommerce加载更多按钮兼容Ajax筛选的修复方案

问题根源在于当前代码依赖页面初始化时的静态查询参数,Ajax筛选后这个参数没有同步更新,导致加载更多请求仍然使用初始的全量商品查询条件。以下是具体修复步骤:

一、修改JavaScript代码:动态获取筛选条件

不再依赖初始化的静态查询参数,每次点击加载更多时,从当前URL提取最新的筛选参数,动态构建请求数据:

(function($) {
"use strict";
$(function() {
    $('#pp_loadmore_products').click(function(){
        var button = $(this),
            // 解析当前URL的查询参数
            currentQuery = new URLSearchParams(window.location.search),
            filterArgs = {};
        
        // 将URL参数转为对象
        currentQuery.forEach(function(value, key) {
            filterArgs[key] = value;
        });

        var data = {
            'action': 'loadmore',
            'page' : wp_js_vars.current_page,
            'filter': filterArgs // 传入最新筛选条件
        };

        $.ajax({
            url : wp_js_vars.ajaxurl,
            data : data,
            type : 'POST',
            beforeSend : function () {
                button.addClass('loading');
                button.text('加载中...');
            },
            success : function( response ){
                if( response.content ) {
                    $('#container_products_more .products_archive_grid').append( response.content );
                    button.removeClass('loading');
                    button.text( '加载更多' );
                    wp_js_vars.current_page++;

                    // 更新总页数(筛选后总页数可能变化)
                    wp_js_vars.max_page = response.max_page;

                    // 最后一页时移除按钮
                    if ( wp_js_vars.current_page >= wp_js_vars.max_page )
                        button.remove();
                } else {
                    button.remove();
                }
            }
        });
    });

    // 补充:筛选完成后重置分页状态(根据你的筛选插件Ajax回调调整)
    // 假设你的筛选插件有成功回调事件,比如'woocommerce_ajax_filter_success'
    $(document).on('woocommerce_ajax_filter_success', function(){
        wp_js_vars.current_page = 1;
        // 如果筛选接口返回总页数,直接赋值:wp_js_vars.max_page = 筛选返回的max_page;
    });
});}(jQuery));

二、修改PHP Ajax处理函数:正确解析筛选参数

替换原有的pp_loadmore_ajax_handler函数,使用WP_Query替代query_posts,并将传入的筛选参数转换为合法的查询条件:

function pp_loadmore_ajax_handler(){
    // 基础产品查询参数
    $args = array(
        'post_type' => 'product',
        'post_status' => 'publish',
        'paged' => $_POST['page'] + 1,
        'posts_per_page' => get_option('posts_per_page'),
    );

    // 合并筛选参数
    if( isset($_POST['filter']) && is_array($_POST['filter']) ){
        foreach($_POST['filter'] as $key => $value){
            // 处理产品分类
            if($key === 'product_cat'){
                $args['tax_query'][] = array(
                    'taxonomy' => 'product_cat',
                    'field' => 'slug',
                    'terms' => $value,
                );
            }
            // 处理产品属性(比如pa_color、pa_size)
            elseif(strpos($key, 'pa_') === 0){
                $args['tax_query'][] = array(
                    'taxonomy' => $key,
                    'field' => 'slug',
                    'terms' => $value,
                );
            }
            // 处理搜索词
            elseif($key === 's'){
                $args['s'] = sanitize_text_field($value);
            }
            // 处理排序参数
            elseif($key === 'orderby'){
                $args['orderby'] = sanitize_text_field($value);
            }
            elseif($key === 'order'){
                $args['order'] = sanitize_text_field($value);
            }
            // 其他自定义筛选参数可在此添加
        }

        // 多筛选条件时设置逻辑关系为AND
        if(isset($args['tax_query']) && count($args['tax_query']) > 1){
            $args['tax_query']['relation'] = 'AND';
        }
    }

    $query = new WP_Query($args);
    $response = array();

    // 捕获产品输出内容
    ob_start();
    if( $query->have_posts() ) :
        while( $query->have_posts() ): $query->the_post();
            wc_get_template_part( 'content', 'product' );
        endwhile;
        wp_reset_postdata();
    endif;
    $response['content'] = ob_get_clean();
    $response['max_page'] = $query->max_num_pages;

    wp_send_json($response);
    die;
}

三、优化初始化参数(可选)

去掉wp_localize_script中不再使用的posts参数,减少冗余:

function pp_custom_scripts_enqueue() {
    $theme = wp_get_theme();

    wp_register_script( 'woocommerce_load_more', get_stylesheet_directory_uri() . '/scripts/load_more.js', array( 'jquery' ), $theme['Version'], true);
    wp_enqueue_script('woocommerce_load_more');
    
    global $wp_query;
    $localize_var_args = array(
        'current_page' => get_query_var( 'paged' ) ? get_query_var('paged') : 1,
        'max_page' => $wp_query->max_num_pages,
        'ajaxurl' => admin_url( 'admin-ajax.php' )
    );
    wp_localize_script( 'woocommerce_load_more', 'wp_js_vars', $localize_var_args );
}

关键注意点

  1. 筛选回调同步:需要根据你使用的Ajax筛选插件,在筛选完成的回调事件中重置wp_js_vars.current_page为1,确保加载更多从筛选后的第一页开始。
  2. 参数安全:所有传入的筛选参数都要做安全处理(比如sanitize_text_field),避免SQL注入风险。
  3. 自定义筛选适配:如果你的筛选有特殊参数(比如价格区间),需要在PHP函数中添加对应的查询逻辑(比如meta_query处理价格)。

内容的提问来源于stack exchange,提问作者Bob Cat

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 10:23:10