[英]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.