PHP While和For循环分组(使用WP ACF)

时间:2015-05-14 12:44:54

标签: php wordpress while-loop advanced-custom-fields

使用' while'循环播放我得到以下输出:

move_it
clean_beauty
on_our_radar
move_it

我想输出这些字段(对于$ featured_type)是相同的。例如。我想输出如下:

move_it
move_it

clean_beauty

on_our_radar

这是我当前使用基本循环输出的第一个示例的示例。我循环遍历字段(来自WordPress中的高级自定义字段中继器)。

        while( has_sub_field( 'featured_posts', $acf_id )  ):


        $featured_post = get_sub_field( 'featured_post', $acf_id );
        $featured_type = get_field( 'editorial_template', $featured_post->ID );

        echo $featured_type . '<br />';

        endwhile;

我已经编写了一些代码组,但知道必须有更优雅的方法来实现相同的结果。我的方式很笨重!任何建议表示赞赏

        <?php 

        while( has_sub_field( 'featured_posts', $acf_id )  ):


        $featured_post = get_sub_field( 'featured_post', $acf_id );
        $featured_type = get_field( 'editorial_template', $featured_post->ID );


        if ($featured_type == 'move_it') {
            echo  $featured_type . '<br />';
        }

        endwhile;

        while( has_sub_field( 'featured_posts', $acf_id )  ):


        $featured_post = get_sub_field( 'featured_post', $acf_id );
        $featured_type = get_field( 'editorial_template', $featured_post->ID );


        if ($featured_type == 'clean_beauty') {
            echo $featured_type .  '<br />';
        }

        endwhile;

        while( has_sub_field( 'featured_posts', $acf_id )  ):


        $featured_post = get_sub_field( 'featured_post', $acf_id );
        $featured_type = get_field( 'editorial_template', $featured_post->ID );


        if ($featured_type == 'on_our_radar') {
            echo  $featured_type .  '<br />';
        }

     endwhile; ?>

1 个答案:

答案 0 :(得分:2)

使用数组,您可以存储值,然后排序并最终回显它们:

$featured_types = array();

while( has_sub_field( 'featured_posts', $acf_id )  ):

    $featured_post = get_sub_field( 'featured_post', $acf_id );
    $featured_type = get_field( 'editorial_template', $featured_post->ID );

    $featured_types[] = $featured_type;

endwhile;

sort( $featured_types );

echo implode( '<br>', $featured_types );

如果您不想按字母顺序排序,可以other ways来执行此操作。