Paul
Paul

Reputation: 45

Add increments to a CSS class

I need to be able to add an increment to a class name. I've looked for solutions for this, and they don't work for my example.

I have a foreach loop in which I want to add a sequential number 1, 2, 3, 4 etc. to the class 'section_0'. Any ideas what I'm doing wrong?

<div class="menu-section-container">


<?php

// check if the repeater field has rows of data
if( have_rows('section_container') ):

// loop through the rows of data
while ( have_rows('section_container') ) : the_row();

    if( have_rows('sub_section_container') ):

    // loop through the rows of data
    while ( have_rows('sub_section_container') ) : the_row();

        if( have_rows('food_item') ):

        // loop through the rows of data
        while ( have_rows('food_item') ) : the_row();

$menu_contents = array( the_sub_field('section_heading'), the_sub_field('item_name'), the_sub_field('price'), the_sub_field('item_description') );

$counter = 1;

foreach ($menu_contents as $menu_content); { ?>

<div id="section_0<?php echo $counter++; ?>" class="tabcontent">
<?php echo $menu_content; ?>
</div>

<?php $counter++; // increment before foreach ends
}

        endwhile;
        else :
        endif;

    endwhile;
    else :
    endif;

endwhile;
else :
endif;

wp_reset_postdata();

?>

</div> <!-- section -->

Upvotes: 2

Views: 1022

Answers (2)

Johannes
Johannes

Reputation: 67748

The $counter variable has to be echoed without the ++:

<div id="section_0<?php echo $counter; ?>" class="tabcontent">

Upvotes: 0

Nigel Ren
Nigel Ren

Reputation: 57121

You probably want to set your $counter further up. So -

$counter = 1;

Would probably be better somewhere like after

if( have_rows('section_container') ):

You can try it in different places to see how it works best for your setup.

Also - in this section of the code, your incrementing $counter twice (using $counter++).

<div id="section_0<?php echo $counter++; ?>" class="tabcontent">
<?php echo $menu_content; ?>
</div>

<?php $counter++; // increment before foreach ends

You can remove one of them and you should get the numbering your after.

Upvotes: 3

Related Questions