Integrate JQuery Masonry in your WordPress theme

Floating divs can be quite frustrating at times.  When these are added side by side, they usually stack as best as they can but they create gaps.

Leveraging JQuery Masonry can help us achieve a much better layout and it’s integration in a WordPress theme is pretty easy. If you’re not familiar with this technique, jQuery masonry allows you to flow blocks of content similarly to a mason wall. It’s pretty neat and there are many great WordPress themes that incorporate it.

I’ve had the chance to work with this technique while working on the Kolke website and a few weeks ago, decided to use this approach for the Threads Gazette redesign.

To incorporate jQuery Masonry in your site, you’ll need to do the following:

1. Download the jQuery script file on their website and insert it in your theme. I personally like to keep all of my javaScript files in a js folder.

2. Enqueue your JQuery by using the following code in your functions.php

wp_enqueue_script('jquery');
wp_register_script('jquery_masonry', get_template_directory_uri(). '/js/jquery.masonry.min.js', array('jquery'), '2.0.110526' );
wp_enqueue_script('jquery_masonry');

3. Insert your JQuery event in your header like so:

<script>
	jQuery(document).ready(function($){
    	$('#container').masonry({
      	  itemSelector: '.box',
    	  });
  	});
</script>

4. Now that you have your jQuery set up, all that’s left is your template and css.

On the threads gazette website, I’ve set up my loop in the index.php and archive.php as follows:

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>

 <div class="box">
	<a href="<?php the_permalink() ?>" rel="bookmark">
			
	<?php if (has_post_thumbnail()) {
		the_post_thumbnail('thumbnail');
	}?>
	<h2><?php the_title(); ?></h2></a>

	</div>

<?php endwhile; endif; ?>

5. A few styles are added to the box class:

.box {
	float:left;
	width: 220px; 
	padding:5px;
	margin:0 10px 10px 0;
	background:#f1f1f1;
}
.box img { 
	max-width: 220px;
	margin:0 auto 0 auto;
display:block;
text-align:center;

 }
.box h2 {
	font-size:14px; 
	line-height:18px;
	margin-bottom:5px;
}

And voila. My boxes now flow beautifully.

If you’re curious about how this all works but would like to do a bit more investigating, check out WP Shower’s Imbalance 2 theme. You can view the demo and download the free theme.

One comment:

Comments are Closed.