按距离对 WooCommerce 产品进行排序

时间:2021-03-01 17:56:08

标签: wordpress woocommerce

我正在开发一个 WooCommerce 多供应商网站,需要能够按与网站访问者的距离对产品进行分类。

  • 我已针对目录中的每个产品存储了纬度和经度值。
  • 我知道访客的经纬度
  • 我知道计算两者之间距离的公式

我的想法是为 WooCommerce 返回的产品添加一个别名字段,可能使用 woocommerce_product_query 挂钩,其中包含与站点访问者的距离,然后对该别名字段进行排序。我知道如何在 SQL 中执行此操作,例如类似的东西:

SELECT *, {FORMULA FOR CALCULATING DISTANCE} AS distance from {TABLE} SORT BY distance;

但我不知道如何使用 WooCommerce 提供的钩子将此别名字段添加到返回的字段中。

有没有人有过实现这一目标或类似目标的经验?或者我从错误的角度接近它!

如果有任何帮助,将不胜感激。

1 个答案:

答案 0 :(得分:0)

所以我终于在这篇文章的帮助下弄清楚了这一点:

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);

您将需要添加一些代码以仅将字段应用于您希望将其应用于的帖子类型,但要点如上。