dongyanju1094 2019-06-05 12:52
浏览 99
已采纳

是否可以通过自定义字段生成的动态值对wp_query循环进行排序/重新排序?

I am trying to find ways to sort my loop from a numeric value(distance) that i can only get via a shortcode(by calculating custom field address). shortcode works, i successfully got the distance value but now i want to sort my data from closest distance to farthest.

i was trying to use usort, but i don't know how to execute it properly.


$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."']");


im expecting to display my data from lowest distance value to highest but right now it doesn't do anything to my loop, just displays the default order. which means my code doesn't work. I would appreciate any help/suggestion

  • 写回答

1条回答 默认 最新

  • duangan2307 2019-06-06 15:49
    关注

    i updated my code, saved the data i needed in array and used 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);
    
    

    now my problem is pagination, since im not using wordpress default loop., but thats for another topic.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 这个复选框什么作用?
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决