0

Looping using a 'while' statment I get the following output:

move_it
clean_beauty
on_our_radar
move_it

I want to output these where the fields (for $featured_type) are the same. Eg. I want to output as follows:

move_it
move_it

clean_beauty

on_our_radar

Here is an example of the first example of what I currently output with a basic loop. I am looping through fields (from an Advanced Custom Field repeater in 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;

I have written some code that does group but know there must be a more elegant way to achieve the same result. My way is clunky! Any advice appreciated.

        <?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 Answer 1

2

Using an array you can store the values, then order and finally echo them:

$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 );

If you don't want to order them alphabetically, there are other ways to do it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.