[英]Is it possible to sort/re-order a wp_query loop by a dynamic value produced from a custom field?
我試圖找到從數值(距離)排序循環的方法,我只能通過短代碼(通過計算自定義字段地址)獲得。 短代碼工作,我成功獲得距離值,但現在我想從最近距離到最遠距離排序我的數據。
我試圖使用usort,但我不知道如何正確執行它。
$loop = new WP_Query( $args );
function customCompare($Aint, $Bint)
{
$Aint = $distance;
$Bint = $distance;
return ($Aint < $Bint);
}
usort($loop->posts, 'customCompare');
while ( $loop->have_posts() ) : $loop->the_post();
$address = get_field('acf_address');
$distance = do_shortcode("[distance address='".$address."']");
我希望將我的數據從最低距離值顯示到最高,但現在它對我的循環沒有任何作用,只顯示默認順序。 這意味着我的代碼不起作用。 我將不勝感激任何幫助/建議
我更新了我的代碼,保存了我在數組中所需的數據並使用了array_multisort
$merchantPost = get_posts( $args );
foreach ( $merchantPost as $post ) :
setup_postdata( $post );
$merchant_list[] = array(
'acf_address' => get_post_meta( $post->ID, 'acf_address', true ),
'distance' => do_shortcode("[distance address_to='".get_field('acf_address')."']"),
'post_title' => get_the_title(),
'permalink' => get_the_permalink(),
'gallery' => get_field('gallery'),
'image' => wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ),
'terms' => get_the_terms( $post->ID, 'merchant_categories' ),
);
endforeach;
wp_reset_postdata();
$all_distance = array();
foreach ( $merchant_list as $mlist ) {
$all_distance[] = $mlist['distance'];
}
array_multisort($all_distance, SORT_ASC, $merchant_list, SORT_NUMERIC);
現在我的問題是分頁,因為我不使用wordpress默認循環。,但那是另一個主題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.