Home > OS >  ACF repeater while loop foreach
ACF repeater while loop foreach

Time:09-05

I'm trying to cover my basic PHP knowledge and I've stucked a bit. I'm trying to connect my this code:

if( have_rows('sales') ):
                while( have_rows('sales') ) : the_row();

                $dataPlatform = get_sub_field('platform');

                endwhile;
endif;

Which is supposed to get all the product platforms from the ACF repeater field (number of values will vary from 1 to approx 5). And add it to this foreach loop:

global $post;

            $terms = get_the_category( $post->ID, 'category' );

            foreach($terms as $term) {
                echo '<div  data-type="'.$term->slug.'" data-platform="">';
            }

Obviously I've tried the easiest approach like the below one:

global $post;

            $terms = get_the_category( $post->ID, 'category' );
            
            if( have_rows('sales') ):
                while( have_rows('sales') ) : the_row();

                $dataPlatform = get_sub_field('platform');

                foreach($terms as $term) {
                    echo '<div  data-type="'.$term->slug.'" data-platform="'. $dataPlatform .'">';
                }
    

                endwhile;
            endif;  

But it doesn't work as I planned. In theory I wanted to have data attribute called data-platform be filled like data-platform="value1 value2.." but my current code breaks the entire design because it duplicates the entire div with the certain values, and nest them.

What I'm doing wrong?

CodePudding user response:

This would make you some divs without closing them. What is the value of $dataPlatform? Also you should be escaping what you echo using esc_attr or esc_html.

foreach($terms as $term) {
  echo '<div  data-type="'.$term->slug.'" data-platform="'. $dataPlatform .'">';
}

Update: Maybe this?

global $post;

$terms = get_the_category( $post->ID, 'category' );
$dataPlatform = "";

if( have_rows('sales') ):
    while( have_rows('sales') ) : the_row();
   
      $dataPlatform .= get_sub_field('platform') . " ";

    endwhile;
    
    foreach($terms as $term) {
        echo '<div  data-type="'.$term->slug.'" data-platform="'. $dataPlatform .'">';
    }    
endif;  
  • Related