【问题标题】:Is it possible to sort/re-order a wp_query loop by a dynamic value produced from a custom field?是否可以通过自定义字段生成的动态值对 wp_query 循环进行排序/重新排序?
【发布时间】:2019-06-05 12:52:44
【问题描述】:

我正在尝试从只能通过简码(通过计算自定义字段地址)获得的数值(距离)中对循环进行排序。短代码有​​效,我成功获得了距离值,但现在我想将我的数据从最近的距离排序到最远的距离。

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


我希望从最低距离值到最高距离值显示我的数据,但现在它对我的循环没有任何作用,只显示默认顺序。这意味着我的代码不起作用。我将不胜感激任何帮助/建议

【问题讨论】:

  • 您不能同时对数据进行循环和排序。您必须先循环一次数据,以便您可以将每个帖子放入一个数组中,并同时添加距离。然后按距离对数组进行排序(继续阅读,PHP 中的排序数组已经详细讨论过),然后循环遍历该数组以生成输出。

标签: php arrays wordpress loops sorting


【解决方案1】:

我更新了我的代码,将我需要的数据保存在数组中并使用了 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 默认循环。但那是另一个主题。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多