Add Class to Elements by Count

Creating dynamic layouts can make it easier on your clients (and yourself) to update your content without worrying about checking the front end to make sure the selections are correct, or having to update various posts / content areas following updating new content.

The following example shows how to add a colour class to your container using the_loop, php and with some CSS adjustments, possibilities are endless!

<div id="wrapper">
		
	<?php $args = array(
		'post_type' => 'voice',
		'posts_per_page' => -1
	); 
	
	$voices = new WP_Query($args);
	
	$counter = 0; // set counter
	
	while($voices->have_posts()) : $voices->the_post(); $counter++; begin counting
	$image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full' );?>
		
		<div class="container
			<?php if ($counter % 4 === 1) {echo 'yellow'; } // every first
				else if ($counter % 4 === 2) {echo 'black'; } // every second
				else if ($counter % 4 === 3) {echo 'red'; } // every third
				else if ($counter % 4 === 4) {echo 'grey'; } // every fourth ?>
		">
			<div class="wrap">
				<?php the_post_thumbnail('medium', array('class' => 'voice_thumb')); ?>
				<div class="content">
					<h3><?php the_title(); ?></h3>
					<?php the_content(); ?>
				</div>
			</div>
		</div><!-- .container -->
	<?php  endwhile; wp_reset_query(); ?>
</div><!-- #wrapper -->

Based off of information found in this thread.

Leave a Reply

Posted in php
katherine as a flat graphic icon

About Me

I’m an African / Ojibwe First Nations Web Developer living in Winnipeg, Manitoba.

Visit the Tips and Blog to see what I’m working on.