Count Items in Array to Create Dynamic Layout

Have you ever wanted to create a layout that updates automatically based on the number of items shown?

$widgets = get_posts(array(
	'post_type' => 'widget',
	'posts_per_page' => -1,
));

$count = 0;

foreach($widgets as $key => $value) {
    $count += $value;
} ?>

<div id="widget_block">
	
	<?php 
		foreach( $widgets as $post ): setup_postdata($post); 
		$image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ); 
	?>
		
		<article style="background-image: url(<?php echo $image[0]; ?>);" class="widget-<?php echo $count; ?>">
			<?php the_title(); ?>
		</article>
	
	<?php endforeach; wp_reset_postdata(); ?>

</div><!-- #widget_block -->

Style the resulting count with CSS.

Source.

Additionally, you could use the count to add a recurring class pattern:

<div class="<?php if(($count % 3) == 0) { echo 'black'; } 
	else if (($count % 3) == 1) { echo 'white'; }
	else if(($count % 3) == 2) { echo 'grey'; }
?>">

 

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.