• Resolved bibliofille

    (@bibliofille)


    I’m using an ACF Pro repeater field to serve blocks of content on a page of my site (each block has a title, some text, an image or video). I called the content using a loop in the page template.

    I’d like to modify that loop to wrap every other block in a div. This is to add a blue background to every other block.

    I’ve done something similar with a php counter, but I have no idea how to implement that this time around. Anyone have advice? Where would I put the php counter?

    Here’s the code from my page template:

    <?php if( have_rows('content_block') ): ?>
    
    	<?php while( have_rows('content_block') ): the_row(); 
    
    		// vars
    		$title = get_sub_field('title');
    		$content = get_sub_field('content');
    		$image = get_sub_field('image');
    		$video = get_sub_field('video');
    
    		?>
    <div class="content-block-item">
    
    				<h4> <?php echo $title; ?></h4>
    			    <p><?php echo $content; ?></p>
    			    <img src="<?php echo $image['url']; ?>"/>
    			    <div class="video"><?php echo $video;?></div>
    			    <button><a href="mailto:info@truetolifetraining.com">get in touch to learn more</a></button>
    		</div>
    
    	<?php endwhile; ?>
    
    <?php endif; ?>
Viewing 4 replies - 1 through 4 (of 4 total)
  • Moderator keesiemeijer

    (@keesiemeijer)

    Try it with this.

    <?php if( have_rows('content_block') ): ?>
    <?php $counter = 0; ?>
    	<?php while( have_rows('content_block') ): the_row(); 
    
    		// vars
    		$title = get_sub_field('title');
    		$content = get_sub_field('content');
    		$image = get_sub_field('image');
    		$video = get_sub_field('video');
    		$class = ( (++$counter % 2) === 0 ) ? " content-block-item-even" : '';
    		?>
    <div class="content-block-item<?php echo $class; ?>">
    
    				<h4> <?php echo $title; ?></h4>
    			    <p><?php echo $content; ?></p>
    			    <img src="<?php echo $image['url']; ?>"/>
    			    <div class="video"><?php echo $video;?></div>
    			    <button><a href="mailto:info@truetolifetraining.com">get in touch to learn more</a></button>
    		</div>
    
    	<?php endwhile; ?>
    
    <?php endif; ?>

    With this you can style the even divs with:

    .content-block-item-even {
    
    }

    Moderator Steven Stern (sterndata)

    (@sterndata)

    Volunteer Forum Moderator

    You can use the nth of type CSS to do this without adding anything to the code:

    http://www.w3schools.com/cssref/sel_nth-of-type.asp

    Moderator keesiemeijer

    (@keesiemeijer)

    Ah yes, even better 🙂

    Thread Starter bibliofille

    (@bibliofille)

    Wonderful! That worked. Completely forgot about nth-of-type. 🙂

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘modify the loop to add div to every other post’ is closed to new replies.