简体   繁体   English

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

[英]Is it possible to sort/re-order a wp_query loop by a dynamic value produced from a custom field?

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. 我试图使用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."']");


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 我将不胜感激任何帮助/建议

i updated my code, saved the data i needed in array and used array_multisort 我更新了我的代码,保存了我在数组中所需的数据并使用了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. 现在我的问题是分页,因为我不使用wordpress默认循环。,但那是另一个主题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM