首页 > 解决方案 > 按距离对 WooCommerce 产品进行排序

问题描述

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

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

SELECT *, {FORMULA FOR CALCULATING DISTANCE} AS distance FROM {TABLE} 按距离排序;

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

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

如果是这样,任何帮助将不胜感激。

标签: wordpresswoocommerce

解决方案


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

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

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


推荐阅读