Tutorial: Using jQuery Masonry with WordPress

This is a short tutorial on integrating Masonry, the jQuery layout plugin, with your WordPress site. We will try to use that jQuery plugin to show a list of posts in a neatly stacked layout, similar to the one I have down here. Here’s an explanation about Masonry, from it’s home page:

Think of it as the flip side of CSS floats. Whereas floating arranges elements horizontally then vertically, Masonry arranges elements vertically then horizontally according to a grid. The result minimizes vertical gaps between elements of varying height, just like a mason fitting stones in a wall.

Here’s a visual explanation, which I took and edited to fit my layout. Pay attention to the numbers, which shows the order of the elements in your HTML code:

Understanding Masonry’s Behaviors

Using Masonry itself is pretty simple, but if it’s the first time you’re using it there can be some surprising behaviors, especially regarding element spacing. Let’s talk about that first.

Masonry allows for two different cases. First is where all elements have the same width, and you should use this:

$('#container').masonry({ singleMode: true });

The second case is where your elements have differend widths. Use:

$('#container').masonry({ columnWidth: 200 });

Where columnWidth is the width of the grid (in pixel). Masonry will then follow these two rules:

  1. Total element width = CSS width + padding-left + padding-right + border-left-width + border-right-width + margin-left + margin-right
  2. When using columnWidth, then all elements must be placed horizontally at an increment of columnWidth (e.g. for columnWidth: 200, elements will start at 0 or 200 or 400 pixels and so on). This might not be intuitive and does not work like CSS float:

    The first element has a total width of 190px and margin-right is 0. At the same time the second element has 0 margin-left, so you will probably expect both to stick to each other. However, since the columnWidth says 200px, then the second element is pushed further and starts at 200px instead.

    That will not be the case if we only have one width, though. The next element will be placed right next to the previous one according to the margin between both.

WordPress + Masonry

Okay, coding time. We’ll try to recreate my Latest Links area where all elements have the same width. First we enqueue jQuery and call the Masonry JS script in the theme’s header.php file.

<?php wp_enqueue_script('jquery'); ?>
<?php wp_head(); ?>
<script language="javascript" type="text/javascript" src="<?php bloginfo('template_url'); ?>/js/jquery.masonry.min.js"></script>

Make sure that wp_enqueue_script appears before wp_head, and the script call appears after it. Here’s a more detailed article on how to correctly enqueue jQuery in WordPress. My Masonry JS is located in a /js folder, yours might be different.

Next, we decide how the HTML will be structured. Mine’s like this:

<div id="linky"> 
 
  <div class="boxy"> 
    <!-- post content -->
  </div> 
 
  <div class="boxy"> 
    <!-- post content -->
  </div> 
 
  ...
 
</div> <!-- #linky -->

Pretty simple. “Linky” will be the container div that will call the Masonry function, and “boxy” will be the elements that will be stacked together. The CSS is where it’s important, you want to make sure the container width and the total element widths match. For example, if you want to have four columns of elements, each having a width + padding of 190px and a margin-right of 10px, then the container will be 200 x 4 = 800px:

1
2
3
4
5
6
7
8
9
10
#linky {
  width: 800px;
  } 
 
  #linky .boxy {
  width: 170px;
  padding: 10px;
  margin-right: 10px;
  margin-bottom: 10px;
  }

Below is my PHP to generate the HTML, I’m using WP_Query to specifically fetch the latest 15 posts from my Links category:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<div id="linky">
 
  <?php
      $linksPosts = new WP_Query();
      $linksPosts->query('showposts=15&cat=7');
  ?>
  <?php while ($linksPosts->have_posts()) : $linksPosts->the_post(); ?>
  <div class="boxy">
    <div class="read">
    <h4><a href="<?php if(get_post_meta($post->ID, "url", true)) echo get_post_meta($post->ID, "url", true); else the_permalink(); ?>"><?php the_title(); ?></a></h4>
      <?php the_content('Read the rest of this entry &raquo;'); ?>               
    </div>
  </div>
  <?php endwhile; ?>
 
</div>

Note that since Masonry saves a lot of space compared to regular floats, you will usually need plenty of elements at once to fill your container (hence 15 in my case).

Now that everything is in place, the last thing to do is to add the Masonry function, preferably right after the script call in header.php:

1
2
3
4
5
<script language="javascript" type="text/javascript" src="<?php bloginfo('template_url'); ?>/js/jquery.masonry.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($){
  $('#linky').masonry({ singleMode: true });
});

And we’re done. Scroll down a little bit (or click here) to see an example; the container and element widths are different from the example CSS above, but you get the general idea.

Resources

Latest Links More →

Rambling Thoughts on Tumblr, WordPress, Posterous, Pinterest and Blogging

Khoi Vinh:

[...] I’ve never been a heavy WordPress user until now. I have to admit, its most recent version is full of the fun, geeky features that I like as a blogger, stuff that allows designer-editors to fully tweak the way content is output. It’s great.

Theme Options – Friend or Foe?

It’s getting quite clear now that the 2012 trend on WordPress theme is less theme options,

Minimising theme options used in themes, coupled with careful consideration of a component’s application in the theme and a selective placement of WordPress filters, allows for a richer theme setup experience for our users while still adding a level of flexibility that is possible to hone in on, should you wish to do so.

…but smarter themes that understand your needs better. Read the rest of the WooThemes post here.

Don’t steal my Theme Options

Andy Adam discusses his experience tweaking and modifying his theme’s options page to better fit the “zero configuration” philosophy. Respect to the Theme Foundry to go to this length thinking about how their theme should work, not just look, for their users.

WordPress End User Security

Dre Armeda’s presentation at the Reno-Tahoe WordCamp 2011. Required reading.

UpThemes Framework, a GPL 2.0-licensed theme options framework for WordPress

This is the kind of framework I’d really love to use: a theme options framework. A wonderful share by UpThemes. Go grab it here.

TwentyEleven Theme

For a while now, a kickass theme has been available for WordPress.com users, called the Duster theme. This theme has been converted for WordPress.org users and seems to be given a new name, the TwentyEleven.

Theming for the Masses

I got plenty of good design and code considerations in this slideshow from Wordcamp Seattle 2011, by Michael Fields. I wish there’s a presentation video somewhere.

Join the WordPress theme review team

Justin Tadlock invites you to join the WordPress theme review team. Any theme submitted to the WordPress.org Theme Directory gets reviewed by this team first, and the deluge of new themes is tough to handle by this small team of twelve.

I am not part of the team, but I’ve taken a look at their process. Being part of the team is without a doubt one of the best way to learn to be a world-class WordPress theme developer. You will learn so much, you begin to notice flaws even in the most popular WordPress themes, and instantly know how to make a better one.

Don’t Mimic Real-World Interfaces

Ben Brooks talks about how creating realistic looking interfaces (like OSX Lion’s iCal) is not necessarily the best option:

It’s great that you spent 16 hours making that wood grain and stainless steel look exactly like the real thing — looks nice — but does your app work? Does your app make sense?

In terms of theme design, things are more lenient. I’d say that we can have a design based on real life objects, sceneries, and so on. But the novelty of it should not take priority over how well the design communicates a site’s content.

Especially important since soon enough, we will stop distinguishing between a website and an app.

What’s wrong with paid WordPress Themes: WooThemes vs ElegantThemes

Not only do the handy internal configuration tools for “quick customization” give clients every opportunity to break their own sites, they carry a lot of overhead. Your CSS files will be bloated as you are always offering the code for two column, three column and six or seven different colours.

The upshot is that these themes are generally not coded for best loading time. They have to include and do so many things (CSS, JS, queries) to cover all the possible combinations due to their huge set of features, every time you open a page, regardless whether you use these features or not!

It’s not that having plenty of features is bad. It’s the inefficiency that can be disadvantageous to the end users.

Technical Web Typography: Guidelines and Techniques

Recommended bookmark material. Covers the technical aspects of setting up typography on the web.

Designing Faster with a Baseline Grid

I’m to working with vertical grid. Not so with adding baseline grid, though, despite it being the key to having a typographic rhythm:

Building a horizontal grid is of course a fundamental step, but creating vertical rhythm is equally important. As Robert Bringhurst wrote in The Elements of Typographic Style: “Don’t compose without a scale”. Type should actually be the scale that defines almost everything else.

Read the article, and directly download their grid here.

Know Your Type: Myriad

Eugene Mosier, production art director at the time praised the typeface for its “proletarian feel,” appropriately dubbing Myriad the “Volkswagen bug of typefaces.”

Read the article here.

Best-Designed Newspaper

Creating a newspaper/magazine-style layout? Take a peek at the World’s Best-Designed Newspaper.

Migrating Your Current WordPress Blog to a WordPress Multisite Blog

Some people want to migrate from normal blog to a Multisite but it is indeed seems complicated. So here’s a detailedly written article, with a helpful video.

Jetpack

Jetpack by Automattic is a plugin that gives your WordPress site features from WordPress.com. I like it, as the features are quite nice and it should be useful for people transitioning from WordPress.com to self-hosted one.