0

我正在尝试组合一个 wordpress SQL 查询,该查询将返回与用户位置相关的结果。

当用户第一次访问该站点时,会设置一个地理位置纬度和经度 cookie。然后将 2 个 cookie 读回到后面页面上的 php 变量中:

$lat = $_COOKIE["lat"];  $long = $_COOKIE["long"];

然后运行以下 sql 代码:

$locations = "
SELECT P.ID, P.post_title, P.post_content,
    MAX(IF(PM.meta_key = 'lat', PM.meta_value, NULL)) AS lat,
    MAX(IF(PM.meta_key = 'long', PM.meta_value, NULL)) AS long,
    MAX(IF(PM.meta_key = 'contact_email', PM.meta_value, NULL)) AS contact_email
FROM wp_posts AS P
LEFT JOIN wp_postmeta AS PM on PM.post_id = P.ID
WHERE P.post_type = 'pickup_location' and P.post_status = 'publish'
GROUP BY P.ID
ORDER BY P.post_title ASC;";
$result_locations = $wpdb->get_results($locations);

到目前为止,一切都在正常工作……正在设置和读取 cookie。查询正在返回它应该返回的内容。但我想将以下内容添加到我的查询中,以进一步缩小查询结果的范围。

AND WHERE acos(sin('.$lat.') * sin('lat') + cos('.$lat.') * cos('lat') * cos('long' - ('.$long.'))) * 6371 <= 200;
4

1 回答 1

0

已经解决了问题。在这里,它适用于其他任何在地理定位、sql、wordpress 和多个 meta_keys 上苦苦挣扎的人。

$lat = $_COOKIE["lat"];
$long = $_COOKIE["long"];
$dist = 200; // This is the maximum distance (in km) away from $lat, $long in which to search
$query = "SELECT
    rl.ID,
    rl.post_title,
    ROUND(6367*2*ASIN(SQRT(POWER(SIN(($lat-lat)*pi()/180/2),2)+
    COS($lat*pi()/180)*COS(lat*pi()/180)*
    POWER(SIN(($long-lng)*pi()/180/2),2))),3) AS distance
FROM
    wp_posts rl
    INNER JOIN (SELECT post_id,CAST(meta_value AS DECIMAL(11,7)) AS lat FROM wp_postmeta lat WHERE lat.meta_key='lat') lat ON lat.post_id = rl.ID
    INNER JOIN (SELECT post_id,CAST(meta_value AS DECIMAL(11,7)) AS lng FROM wp_postmeta lng WHERE lng.meta_key='long') lng ON lng.post_id = rl.ID
WHERE
    rl.post_type='pickup_location' AND rl.post_status='publish' 
    HAVING distance <$dist
ORDER BY
    distance ASC LIMIT 2; ";

$result_locations = $wpdb->get_results( $query );
于 2017-05-31T01:38:22.957 回答