ACF谷歌地图搜索插件posts_orderby未生效,商品按距离排序异常
I see exactly what's happening here—WooCommerce's default catalog sorting is taking precedence over your custom distance-based orderby clause. The posts_orderby filter your plugin uses runs at the default priority of 10, but WooCommerce applies its own sorting logic later (usually with a higher priority or via dedicated hooks), which overwrites your changes.
Here are two reliable fixes to get your distance sorting working:
Solution 1: Boost the Priority of Your posts_orderby Filter
By increasing the priority of your custom filter to a higher number (like 99), you ensure it runs after WooCommerce's default sorting logic, effectively overwriting it when lat/lng parameters are present.
Update your existing acf_google_maps_search_orderby_WPQuery filter registration:
// ORDER BY DISTANCE function acf_google_maps_search_orderby_WPQuery($orderby) { if ( isset($_GET['lat']) && !empty($_GET['lat']) && isset( $_GET['lng']) && !empty($_GET['lng']) ) { $lat = sanitize_text_field( $_GET['lat'] ); $lng = sanitize_text_field( $_GET['lng'] ); $orderby = " (POW((acf_gms_geo.lng-{$lng}),2) + POW((acf_gms_geo.lat-{$lat}),2)) ASC"; } return $orderby; } // Set priority to 99 to run after WooCommerce's default sorting add_filter('posts_orderby', 'acf_google_maps_search_orderby_WPQuery', 99);
Solution 2: Use WooCommerce's Dedicated Sorting Hook
If the first solution doesn't work (some WooCommerce setups use more aggressive sorting overrides), you can hook directly into WooCommerce's catalog ordering system to replace the sort logic conditionally.
Add this code alongside your existing plugin functions:
// Override WooCommerce catalog sorting when lat/lng parameters exist add_filter('woocommerce_get_catalog_ordering_args', 'override_woocommerce_sort_for_distance', 99); function override_woocommerce_sort_for_distance($args) { // Only apply when lat and lng are present in the URL if ( isset($_GET['lat']) && !empty($_GET['lat']) && isset( $_GET['lng']) && !empty($_GET['lng']) ) { // Clear WooCommerce's default orderby/order values $args['orderby'] = ''; $args['order'] = ''; // Ensure our distance sort filter runs with high priority add_filter('posts_orderby', 'acf_google_maps_search_orderby_WPQuery', 99); } return $args; }
Why This Works
Looking at your provided SQL query, the ORDER BY clause is set to wp_postmeta.meta_value+0 DESC, wp_posts.post_date DESC—this is WooCommerce's default sorting (likely sorting by total sales first). By either boosting your filter's priority or using WooCommerce's own hook to disable default sorting when needed, you force the query to use your distance-based calculation instead.
After applying either fix, your SQL's ORDER BY should update to:
ORDER BY (POW((acf_gms_geo.lng-6.640710899999931),2) + POW((acf_gms_geo.lat-43.26768079999999),2)) ASC
内容的提问来源于stack exchange,提问作者Jeff

