wordpress - 按距离对 WooCommerce 产品进行排序
问题描述
我正在开发一个 WooCommerce 多供应商网站,需要能够按与网站访问者的距离对产品进行分类。
- 我针对目录中的每个产品存储了纬度和经度值。
- 我知道来访者的经纬度
- 我知道计算两者之间距离的公式
我的想法是为 WooCommerce 返回的产品添加一个别名字段,可能使用 woocommerce_product_query 挂钩,其中包含与网站访问者的距离,然后对该别名字段进行排序。我知道如何在 SQL 中做到这一点,例如:
SELECT *, {FORMULA FOR CALCULATING DISTANCE} AS distance FROM {TABLE} 按距离排序;
但我不知道如何使用 WooCommerce 提供的挂钩将此别名字段添加到返回的字段中。
有没有人有过实现这个或类似的经验?或者也许我从错误的角度接近它!
如果是这样,任何帮助将不胜感激。
解决方案
所以我终于在这篇文章的帮助下弄清楚了这一点:
https://xplus3.net/2010/08/08/filtering-on-a-non-standard-database-field-with-wordpress/
要向 WP_Query 添加一个额外的别名字段,您需要连接到 posts_fields ,它允许您修改正在查询的 SELECT 部分,例如
function my_posts_fields( $fields, $query ) {
$userlat = {Users Lat};
$userlong = {Users Long};
$destlat = {Destination Lat};
$destlong = {Destination Long};
$fields .= sprintf(",( 3959 * acos( cos( radians( %f ) ) * cos( radians( %f ) ) * cos( radians( %f ) - radians( %f ) ) + sin( radians( %f ) ) * sin( radians( ".$wpdb->prefix."gmw_locations.latitude ) ) ) ) ) AS distance", $destlong, $userlat, $destlat, $destlong, $userlong, $userlat, $destlat);
return $fields;
}
add_filter('posts_fields', 'my_posts_fields', 10, 2);
然后要对这个新字段进行排序,您需要连接到 posts_orderby ,它允许您修改查询的 ORDER BY 部分,例如
function my_posts_orderby( $orderby, $query ) {
$orderby = "distance ASC";
return $orderby;
}
add_filter('posts_join', 'my_posts_join', 10, 2);
您将需要添加一些代码以仅将字段应用于您希望将其应用于的帖子类型,但要点如上。
推荐阅读
- autodesk-forge - 使用设计自动化 API 从 Revit 模型导出明细表
- powerbi - Microsoft Power BI:RANKX 和结果聚合
- typescript - 如何声明具有可变数量属性的 TypeScript 接口?
- python - 如何在特定索引后将数字附加到 txt 文件
- unity3d - AR Foundation 4.0.2 使用 Unity2019.3 更新问题 TestCameraImage
- azure - Azure IoT 中心 - 如果在 IoT 中心设置了路由,则 IoTHubTrigger Azure 函数不会执行
- c - 在 C 中调用 abort() 时如何指定消息?
- google-bigquery - 使用 gmail 日志和 BQ 审核 SMTP 中继中的条目
- python - 我可以在转换为 dict 时省略的数据类中的可选参数吗?
- python - 预期输入 batch_size (32) 与目标 batch_size (19840) BERT 分类器匹配