WordPress and jQuery Masonry setup with floating images

The Masonry jQuery plugin is an easy way to stack divs in a nice grid without the usual problem with CSS floats – e.g divs with different heights will not look good beside each other.

In a recent project a client wanted WordPress thumbnails stacked in this way. I first added some code to functions.php in order to set widths and heights to the selected thumbnails.

 // this goes into functions.php
add_image_size( 'front-thumb', 150, 9999 ); //150 pixels wide (and unlimited height)

UPDATE 20 DEC 2011:

// this goes on top of the page, either to header.php or on top of the specific page template

<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="jquery.masonry.min.js"></script>


<script type="text/javascript">
jQuery(document).ready(function($){

  var $container = $('.front-box-container');
  $container.imagesLoaded( function(){
    $container.masonry({
      itemSelector : '.front-box',
      singleMode:true
    });
  });

});
</script>

// On the specific page or category archive create a new loop and create the markup for Masonry to catch:

<?php query_posts(array('paged' => get_query_var('page'),'posts_per_page' => 25, 'cat'=> '-3' ) ); ?>

<div class="front-box-container">
<ul class="front">
<?php while ( have_posts() ) : the_post(); ?>

<div class="front-box">
    <li<?php if (! has_post_thumbnail()){echo (' class="front-noimage"');}?>>
    	<a href="<?php the_permalink() ?>">

    	   	<?php the_post_thumbnail('front-thumb'); ?>
    	        <div class="front-info">
            <h2><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2>
            <div class="alternate-content"><?php the_excerpt(); ?></div>
        </div>
    </li>

</div>

<?php endwhile;
wp_reset_query(); ?>

</ul>
</div> <!-- front-box-container -->

That should make the images with (.front-box) inside the parent div (.front-box-container) float nicely with Masonry. Good luck!

3 comments

  1. Hi,

    Can’t seem to get this working.

    Do you have a page template I can use?
    Where do I put: query_posts(array(‘paged’ => get_query_var(‘page’),’posts_per_page’ => 25, ‘cat’=> ‘-3’ ) );

    Thanks

    R

  2. I have been trying tutorial after tutorial and can not get this to work in my wordpress child theme.

Post a comment

You may use the following HTML:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>