2016-04-02 6 views
2

投稿に距離別ソートを行っています。シナリオは次のようなものです。ユーザーが都市名を入力すると、都市の座標が取得されます。各ポストにはポストメタとしての座標もあります。私はこれら2つのポイントの間の距離を見つけて、最低距離の投稿などの投稿を最初に表示する必要があります。Wordpress WP_Queryによって返された投稿を並べ替えます。

距離の計算には次のコードを試してみました。私の問題は、この距離をポストに付けることです。投稿オブジェクトにプロパティを追加しようとしました。しかし、どのようにこの投稿を並べ替えるには?

ソートされた投稿でWP_Queryオブジェクトが必要です。

$ prop_selection = new WP_Query($ args);

while ($prop_selection->have_posts()): $prop_selection->the_post(); 

    $property_lat = get_post_meta($post->ID,'property_latitude',true); 
    $property_lng = get_post_meta($post->ID,'property_longitude',true); 

    $distancefromcity=distance($property_lat,$property_lng,$city_lat,$city_lng,"K"); 
    $distancefromcity=round($distancefromcity,2); 

    $post = (array)$post; 
    $post['distance'] = $distancefromcity; 
    $post = (object)$post; 

endwhile; 

答えて

1

を参照してください、私はそれは次のようでした。 これはOkですか、それとも良い方法がありますか?

while ($prop_selection->have_posts()): $prop_selection->the_post(); 

     $property_lat = 0; 
     $property_lng = 0; 

     $property_lat = get_post_meta($post->ID,'property_latitude',true); 
     $property_lng = get_post_meta($post->ID,'property_longitude',true); 

     $distancefromcity=distance($property_lat,$property_lng,$city_lat,$city_lng,"K"); 
     $distancefromcity=round($distancefromcity,2); 
     $distance_array[]= array('ID' => $post->ID, 
           'distance' => $distancefromcity); 

    endwhile; 


    usort($distance_array, function ($item1, $item2) { 
     if ($item1['distance'] == $item2['distance']) return 0; 
     return $item1['distance'] < $item2['distance'] ? -1 : 1; 
    }); 


    $sorted_posts = array(); 

    foreach($distance_array as $key) 
    { 
     $sorted_posts[]=$key['ID']; 
    } 


    $args = array(
     'cache_results'   => false, 
     'update_post_meta_cache' => false, 
     'update_post_term_cache' => false, 
     'post_type'    => 'estate_property', 
     'post_status'    => 'publish', 
     'paged'     => $paged, 
     'posts_per_page'   => $prop_no, 
     'post__in'    => $sorted_posts, 
     'orderby'     => 'post__in' 
    ); 

    $prop_selection = new WP_Query($args); 
+0

これはいいと思います。しかし、あなたのサイトでは、不要なオーバーヘッドだと思われるリクエストごとにこの並べ替えを実行することを忘れないでください。ポストメタデータメソッドを使用した場合は、各リクエストに対して1つのクエリのみが使用されます。 –

+1

実際にユーザーは複数の都市を検索します。ポストメタを追加するとオーバーヘッドが増える可能性があります(「ユーザーは都市名を入力しました」というときは、初めてではなく複数回検索します) –

+0

この場合、あなたの方法は理にかなっています。 –

関連する問題