从子页面的自定义字段wordpress循环中删除重复结果


Strip duplicate results from custom field wordpress loop of child pages

我正在循环浏览当前页面的所有子页面。我正在返回自定义字段"卧室"的结果。这就产生了一个数字列表(卧室数量),比如131413。这就是我所期望的。

然而,我想删除重复项,因此在上面的示例中,它将返回为134。

我研究过数组,但在php方面不是最好的,所以有人能帮忙吗?

这是我当前用于子循环和acf字段返回的代码。

           <?php
            $args = array(
                'post_type'      => 'property',
                'posts_per_page' => -1,
                'post_parent'    => $post->ID,
                'orderby'       => 'plot_number',
                'order'         => 'ASC'
             );     
            $parent = new WP_Query( $args );    
            if ( $parent->have_posts() ) : ?>
            <?php while ( $parent->have_posts() ) : $parent->the_post(); ?>
                 <?php the_field('bedrooms'); ?>
            <?php endwhile; ?>
            <?php endif; wp_reset_query(); ?>

我的建议是将数字放入一个数组中(你在问题中提到了这个想法)。

我使用implode()来连接数组的元素,使用一个空字符串(没有空格)作为粘合剂。我还使用array_unique()函数返回一个没有重复的新数组。

还要注意使用get_field(),它将返回字段值,而不是the_field(),它将输出字段值。

示例:

<?php
$bedrooms = array();
while ( $parent->have_posts() ) : $parent->the_post();
    // Add 'bedrooms' field value to the array.
    $bedrooms[] = get_field( 'bedrooms' );
endwhile;
// Output as string with no spaces and duplicates removed.
echo implode( '', array_unique( $bedrooms ) ); ?>