为Divi的WooCommerce产品模块添加自定义筛选器遇问题求助
解决Divi产品模块不显示位置筛选结果的问题
你的核心问题在于:没有正确修改现有查询对象,而是创建了新的WP_Query实例,且未适配Divi产品模块的专属查询逻辑。以下是具体修正方案:
1. 错误代码分析
你当前的函数直接实例化了新的WP_Query并返回,但woocommerce_product_query和pre_get_posts钩子的作用是修改传入的现有查询对象,而非返回新对象。同时Divi产品模块使用独立的查询逻辑,不会自动读取主查询的修改结果。
2. 修正后的代码实现
方案一:适配WooCommerce主查询(适用于默认店铺页面)
function add_filter_to_product_search($query, $query_vars) { // 仅在前端产品相关页面生效 if (is_admin() || !is_post_type_archive('product') && !is_tax(array('product_cat', 'product_tag'))) { return; } $distance = isset($_GET['distance']) ? intval($_GET['distance']) : 0; if ($distance <= 0) { return; } $lat = isset($_GET['lat']) ? floatval($_GET['lat']) : 0; $lng = isset($_GET['lng']) ? floatval($_GET['lng']) : 0; if ($lat == 0 || $lng == 0) { return; } $coords = get_coords($lat, $lng, $distance); // 直接修改传入的查询对象参数 $query->set('posts_per_page', 21); $query->set('meta_query', array( 'relation' => 'AND', array( 'key' => 'latitude', 'type' => 'DECIMAL', 'value' => [$coords[1], $coords[0]], 'compare' => 'BETWEEN', ), array( 'key' => 'longitude', 'type' => 'DECIMAL', 'value' => [$coords[2], $coords[3]], 'compare' => 'BETWEEN', ) )); } add_action('woocommerce_product_query', 'add_filter_to_product_search', 10, 2);
方案二:适配Divi产品模块(关键修复)
Divi产品模块使用独立的查询逻辑,必须通过其专属钩子修改参数:
function divi_product_module_location_filter($query_args) { $distance = isset($_GET['distance']) ? intval($_GET['distance']) : 0; if ($distance <= 0) { return $query_args; } $lat = isset($_GET['lat']) ? floatval($_GET['lat']) : 0; $lng = isset($_GET['lng']) ? floatval($_GET['lng']) : 0; if ($lat == 0 || $lng == 0) { return $query_args; } $coords = get_coords($lat, $lng, $distance); // 合并原有meta_query(避免覆盖其他筛选条件) $meta_query = isset($query_args['meta_query']) ? $query_args['meta_query'] : array(); $meta_query['relation'] = 'AND'; $meta_query[] = array( 'key' => 'latitude', 'type' => 'DECIMAL', 'value' => [$coords[1], $coords[0]], 'compare' => 'BETWEEN', ); $meta_query[] = array( 'key' => 'longitude', 'type' => 'DECIMAL', 'value' => [$coords[2], $coords[3]], 'compare' => 'BETWEEN', ); $query_args['meta_query'] = $meta_query; $query_args['posts_per_page'] = 21; return $query_args; } add_filter('divi_woocommerce_products_query_args', 'divi_product_module_location_filter');
3. 关键注意事项
- 不要创建新WP_Query:钩子的设计是通过引用修改现有查询,重新实例化的查询不会被页面模块读取。
- 移除
wp_reset_postdata():该函数用于循环后恢复原始查询,在查询修改阶段调用会破坏现有逻辑。 - 双重适配:如果你的页面同时使用默认WooCommerce店铺页面和Divi产品模块,需要同时添加上述两个函数。
内容的提问来源于stack exchange,提问作者James Feudo
相关产品推荐
相关产品推荐

