Laying out a grid in WordPress

For a recent project, I needed to lay items out in a series of grids, sometimes three columns, sometimes more. The CSS provided by the designer looked something like this:

.columns section {
float: left;
margin-left: 20px;
width: 220px;
}
.columns section.one {
clear: left;
margin-left: 0;
}

I could have used jQuery, or some of the more advanced CSS selectors, to achieve this, but here’s what I created as a custom WordPress template tag.

/**
* Cycle through the values in a list, printing each in turn.
*
* @param array $cycle The options to cycle through
* @param int $count An incrementing counter
* @return mixed Depends what values were provided in the array for $cycle
* @author Simon Wheatley
**/
function sil_cycle( $cycle, $count = null ) {
echo get_sil_cycle( $cycle, $count );
}

/**
* Cycle through the values in a list, returning each in turn.
*
* @param array $cycle The options to cycle through
* @param int $count An incrementing counter
* @return void (echoes)
* @author Simon Wheatley
**/
function get_sil_cycle( $cycle, $count = null ) {
global $wp_query;
if ( is_null( $count ) )
$count = $wp_query->current_post;
return $cycle[ (int) $count % count( $cycle ) ];
}

I put the code above into the theme functions.php file, but you could also create a little plugin so it’s reusable across projects.

I always like to follow the pattern of one function which returns the value, and one which echoes, as this means I cover all my bases and I avoid having something in my templates like <?php echo sil_cycle(); ?> which doesn’t feel like neat code to me.

To use the template tag in the loop is dead simple, you just need to supply the values to cycle through like this:

<?php while ( have_posts() ) : the_post(); ?></code>

<section class="<?php sil_cycle( array( 'one', 'two' ) ); ?>">
<?php get_template_part( 'content', get_post_format() ); ?></section><?php endwhile; ?>

Note that in the normal post loop you don’t need to supply the $count parameter. If you want to use this cycling template tag in a custom WP_Query loop, it’s still pretty easy. You just need to add a second parameter which passes the current_post property from your query as the counter, like this:

<?php $query = new WP_Query( 'tag=cooking' ); while ( $query->have_posts() ) : $query->the_post(); ?></code>

<section class="<?php sil_cycle( array( 'one', 'two' ), $query->current_post ); ?>">
<?php get_template_part( 'content', get_post_format() ); ?></section><?php endwhile; ?>

So there you have it. It’s a simple bit of code, but something I found useful and I hope you do too.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.