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 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题