Question

I have this function that gives a specific number to every item of a loop.

<?php $counter =0; ?>
<?php while( have_rows('profs_associes') ): the_row(); ?>
  <?php
    ++$counter; 
    if($counter == 1) {$imageclass = 'data-contentid="1"';}
    if($counter == 2) {$imageclass = 'data-contentid="2"';}
    if($counter == 3) {$imageclass = 'data-contentid="3"';}
    if($counter == 4) {$imageclass = 'data-contentid="4"';}
    if($counter == 5) {$imageclass = 'data-contentid="5"';}
    if($counter == 6) {$imageclass = 'data-contentid="6"';}
    if($counter == 7) {$imageclass = 'data-contentid="7"';}
    if($counter == 8) {$imageclass = 'data-contentid="8"';}
    if($counter == 9) {$imageclass = 'data-contentid="9"';}
    if($counter == 10) {$imageclass = 'data-contentid="10"';}
?>
<div class="img-row" <?php echo $imageclass; ?>>

But it seems it could be simplified (I have to do a lot of it) by simply writing one function that sets the number of the item as a the 'id' of said item. Can anybody help ?

Was it helpful?

Solution

Just assign the value of the counter into the relevant place:

<?php while( have_rows('profs_associes') ): the_row(); ?>
  <?php
    ++$counter; 
    $imageclass = 'data-contentid="'.$counter.'"';

OTHER TIPS

++$counter; 
$imageclass = 'data-contentid="'.$counter.'"';

I believe this is what you are trying to do. The . operator concatenates the value of $counter to the string.

You have a lot of open and close php tags, you dont need do that (at all actually).

<?php
$counter =0;
while( have_rows('profs_associes') ): the_row();// Not really sure what's going on here
    ++$counter; 
    $imageclass = 'data-contentid="'.$counter.'"';
    echo '<div class="img-row" '.$imageclass.'>':
}
?>

You could minimize even further:

<?php
$counter =0;
while( have_rows('profs_associes') ): the_row(); 
    echo '<div class="img-row" data-contentid="'.(++$counter).'">':
}
?>

And if you only want to loop 10 times, we have the for():

<?php
for($counter=1; $count<=10; $counter++){
    echo '<div class="img-row" data-contentid="'.$counter.'">':
}
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top