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.

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

报告相同问题?