Feb
10
2012

PHP Grid with Modulus and WordPress

Creating a layout in WordPress can be a simple, or complicated task. This quick tip will show you how to use modulus and PHP within WordPress to create a grid for your posts and images. We will use a single variable to set how many grid columns to use or, in even simper terms, how many items to display across horizontally before we move to the next line.

PHP Modulus is an arithmetic operator that gives the remainder of number A divided by number B. If a number can be equally divided into another number then the remainder will be zero. As examples:

3 / 3 == 1

5 / 3 == 2.5

3 goes into 3 once and leaves no remaining number during the operation. While 3 goes into 5 once, and leaves 2 remaining. We will be using this logic to create our PHP grid in WordPress to display our posts. We will use the following interpretation:

increment / columns

Thus, if we have 10 posts and want to display 4 across before moving to the next line we will print each post across until the number equals 0. So the calculations occurring will look like this:

1 / 4 = 0.25

2 / 4 = 0.5

3 / 4 = 0.75

4 / 4 = 1

When we reach 1 that means the number divides equally into the other and leaves 0 remaining. With 0 remaining we know we have reached 4 items across, or columns, and can move to the next. Remember – we are using the PHP modulus to determine what number remains and use that number in our conditional statement within WordPress.

<?php 
query_posts( 'posts_per_page=8' ); 
$columns = 4;
$increment = 0;
?>
	<table>
		<?php if(have_posts()) : while(have_posts()) : the_post(); ?>
			<?php if($increment % $columns == 0){ // if increment is divisable by columns (ie 3/3 = 0))?>
			<tr>
				<td>
					<div class="post" id="<?php the_ID(); ?>">				
					<div class="entry">
						<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>					
					</div>
				
					</div> <!-- .post -->
				</td>
			
			<?php
			}else{
			?>
				<td>
					<div class="post" id="<?php the_ID(); ?>">				
					<div class="entry">
						<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>					
					</div>
				
					</div> <!-- .post -->				
				</td>				
			
		<?php }$increment++; endwhile; endif;?>
	</tr></table>

We define our number of columns before the loop and then set our increment counter to 0 because all arrays start at 0, including results from our WordPress query. We then add table tags before the loop, and close the table and row tag after the loop. You can use any method of display, including using a DIV and floats. For this tutorial we are keeping it simple and using a table.

Because we start our increment at 0 the first post will display because the PHP modulus returns 0. Zero divided by any number is zero! This lets us initiate our next tag element in our table grid. We open our first post with a TR and TD. We finish that post by closing our TD tag but not the TR. We don’t know, yet, if we have reached the amount of items to show in the first row so we don’t want to close off the row until we do.

We finish that action by adding 1 to our increment variable and then WordPress continues it’s while() loop. This time around it finds a remainder and so moves on to the else statement. It will continue to do this until we have a remainder of zero once again. Using the above number of posts we will have 2 rows of 4 posts, and the last row will have 2 posts. There. A nice and easy way to add a grid layout to your posts!

As a bonus, using the same logic, I have a quick snippet for you to use to display an image from a post instead of the title! Great for gallery pages or even displaying related posts.

	<div id="content" style="margin-left:-4px;width:1014px;padding:0px;">
       <table width"100%">
          
		<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
			          <?php
				          $args = array(
							'numberposts' => -1, //the amount of images to retrieve
				    		'post_type' => 'attachment', //defined post type
				    		'status' => 'publish', //the status of the post (draft, published, etc)
				    		'post_mime_type' => 'image', //e.g. image, video, video/mp4
				    		'post_parent' => $post->ID, //the ID of the post we want to use
							'order'=> 'ASC',
			                'orderby' => 'title'
							);
							$images = &get_children($args); //post is the parent, and attachments are children of parent.  Get the children
						 //loop through the post attachments				
					     
					?>

	       <?php 
		   if($increment % $columns == 0) // if increment is divisable by columns (ie 3/3 = 0))
		   {
					echo '<tr><td style="text-align:left;">';
                           			
							foreach ( (array) $images as $attachment_id => $attachment )
							{ 
							$img_desc = $attachment->post_content;
							$image_attributes_medium = wp_get_attachment_image_src( $attachment_id, 'thumbnail' );
							$image_attributes = wp_get_attachment_image_src( $attachment_id, 'full' );
							echo '<a class="grouped" rel="gallery'.$increment.'" href="'.$image_attributes[0] .'"title="'. $img_desc.'">';					
							echo '<img src="'.$image_attributes_medium[0].'" title="" /></a></td>';  				  
							 }
		   }
		   else
		   {
					echo '<td style="text-align:center">';
                           			
							foreach ( (array) $images as $attachment_id => $attachment )
							{ 
							$img_desc = $attachment->post_content;
							$image_attributes_medium = wp_get_attachment_image_src( $attachment_id, 'thumbnail' );
							$image_attributes = wp_get_attachment_image_src( $attachment_id, 'full' );
							echo '<a class="grouped" rel="gallery'.$increment.'" href="'.$image_attributes[0] .'"title="'. $img_desc.'">';					
							echo '<img src="'.$image_attributes_medium[0].'" title="" /></a></td>';  				  
							 }
		   }
		   
			 
				$increment++;
		   ?>
		
		<?php endwhile; endif; ?>	
</tr></table>  </div>

Have fun and happy coding! As usual, please don’t hesitate to provide feedback or let me know if my tips are helping you in your projects.

Related posts:

About the Author: Neil Davidson

Neil Davidson writes articles and tutorials about web development. He is happily married with three dogs, two cats and an ominous spirit in his home.

7 Comments + Add Comment

  • Hi Neil, This code solved my problem as I was looking for it since months. There is little problem as it gives latest posts. I want to put this on category page, so how can I amend it to display posts of specifically that category.

    • The loop will use the most recent query available by default. I use, in the examples, two different approaches to the query itself: The first uses query_posts() and the second uses the global $post which is available when a post or page loads in wordpress.

      For custom queries you need to decide what method you wish to use, as WordPress provides many different built-in query functions.

      If you are on the category page, or archive page, the global variable $wpdb is accessed by default. This uses the wpdb class and is used for many wordpress queries. Now..that’s just specific mumbo-jumbo. On to the solution:

      You might write a custom query at the top of the page above the loop using something like query_posts( array ( ‘category_name’ => ‘The Category Name’, ‘posts_per_page’ => -1 ) );

      You could also use wp_query(). This is usually my preference unless I need access to the wpdb class itself.

      You could create a page template for category. ie: category-news.php, category-profile.php, category-blog.php…etc.

      As you can see there are many ways to acheive what you are looking for regarding a query of information. I’ve barely even touched the available methods you could use. As for the relationship with this article? The modulus usage is for layout and really has nothing to do with where the information comes from, what query is used, or what color your car is !

  • Hi,
    I am looking for a solution for changing my gallery look a bit like this: http://ma.tt/gallery/ Maybe you can help me? First I have to confess I am a bloody beginner – I do my customizing as far as I understand diverse turorials by using copy and paste..
    So here’s my question
    How can I create a “Photo set”? or, perhaps easier, a gallery column within a column?
    Actually I have a lot of thumbnails in my fotoblog and I want to change the look – a bigger photo on the left and two or four thumbnails on the right. I tried to do it by this:
    [two_columns_one] – upload of phot size medium – [/two_columns_one] [two_columns_one_last] [gallery columns="2" id"23,24,25,26" [/two_columns_one_last]

    unfortunately it won’t work. What you see on the right side ist the text of the html code.
    I would be thankful for any help!
    Sylvia

    • Hey,

      For starters you miss a key ingredient to wordpress: The Loop. Understanding that will help you understand why simply using shortcode tags from a template you bought simply won’t work for what you are trying to do.

      Understanding how wordpress handles images would be the second piece of information you will want to learn. Such as that uploading an image typically gets turned into 4 images by wordpress: thumbnail, medium, large, and the original image.

      To do what you are asking there are lots of different ways so I will just give a clue how I would approach it, initially.

      The first thing I would do is set up either a custom post type or unique category structure, or both. I would also create a custom page template to display our galleries. Why? I like to seperate content – so a custom post type moves gallery images and such outside of blog posts and other posts. Plus it allows a bit easier querying of the database. The custom page is just because I like seperating custom code into relevant template types for easy editing years down the road.

      I’d then create a loop on the page template that goes through all the custom gallery posts by category, name, or whatever criteria and disaply a single medium-large image on the left, and the rest would be on the right displayed as thumbnails.

      To make it even more contained I would attach multiple images to a single post and loop through each post, displaying the first image large and the remaining attachments/children as thumbnails.

      Cool. That handles the layout. Next is what you want to do when someone moves their mouse over, clicks, and so on.

      There’s a bit involved in programming, my friend. Lots of planning goes in to making it look easy!

      • Hi,
        thank you very much for your detailed answer! The suggested pattern for the beginning and, I got it, just studying a book about html/css…

  • Hi there,

    This is so helpful, thank you!

    My one question is how you managed to close the tag after each row. I replaced your code with divs and spans, and they will not autoclose for me after the four columns are displayed. I am left with a row inside of another row!

    Thanks,

    Alyssa

    • Hi Alyssa,

      Not sure what your code looks like but here is another way to see the script using Divs: (which you can easily modify the line break in your CSS for the first item with something like .blocks:first-child )

      comments and pasting code isn’t set for my site yet. Might have to do that…

      anyway, here it is in paste bin:
      http://pastebin.com/0cTVbTaX

Leave a comment