Using jQuery Masonry for Pinterest-Like Posting

Using jQuery Masonry for Pinterest-Like Posting

Tutorial Details
  • Version: Wordpress 3.5
  • Difficulty: Beginner
  • Estimated Completion Time: 20 minutes

With the inclusion of jQuery Masonry in the WordPress 3.5 core library, it’s never been easier to change up a template’s layout for recent posting.


Serving up your content in a masonry layout can make the blog portion of your website more visually interesting for your readers. With jQuery Masonry, it doesn’t matter the length of your post excerpt (within reason of course), it will adjust to fill every bit of space. This tutorial is going to explore the idea behind using the newly included jQuery Masonry library with WordPres 3.5.


What Is a Masonry Layout?

If you’ve heard of a “masonry” wall (think of a brick wall), then you have a pretty good mental image of what a masonry layout on your website might look like. If you’re still confused, visit Pinterest and check out how they’ve laid out each “pin” on their website. Everything is arranged vertically, filling up all available space. It’s important to note the term “vertical” in that last sentence. You can achieve the same type of masonry effect using CSS floats, but you might run into spacing issues. This happens because, unlike jQuery Masonry, CSS floats will arrange elements horizontally first, then vertically. This can make for very inconsistent and sometimes unwanted gaps of space in your layout. Using jQuery Masonry can help solve this problem.

CSS Float Example


Notice how there are gaps between posts of varying heights when you use CSS floats.

jQuery Masonry Example


With jQuery Masonry each post fits nicely into place, leaving no awkward gaps.

Now that we know what a Masonry layout is, let’s get started creating a simple, jQuery Masonry layout for our recent posts.


Step 1 Using wp_enqueue_script to Load the Library

Before we can start building our wall we need to load the appropriate script. You’ll need to add the following code to your functions.php file.

	function mason_script() {
		wp_enqueue_script( 'jquery-masonry' );
	}
	add_action( 'wp_enqueue_scripts', 'mason_script' );

Step 2 Setting Up the Grid

For my basic masonry structure, I’m going to implement the following HTML into my loop (or custom template – wherever you plan to build your wall). First, I’m going to set the container for the masonry wall and then setup the container for each post within the wall.

	<div id="container">
		<!-- start your query before the .brick element -->
		<div class="brick">
			<!-- Post Content -->
		</div>
		<!-- end query-->
	</div>

Setting Up Your CSS

You’ll need to define your container width and post width to achieve the actual masonry effect. For my demo, I’ve set my container to 960 pixels wide and I want to have 4 columns of posts. So, I need to do some simple math to find what size width each post on my wall should be.

Brick width = 960px / 4 posts = 240 pixels each.

With that number in mind, I can set my layout up in my stylesheet:

	#container {
		width:		960px; // width of the entire container for the wall
	}

	.brick {
		width:		220px; // width of each brick less the padding inbetween
		padding:	0px 10px 15px 10px;
	}

Step 3 Setup the Function

Next, we need to setup the masonry function so that our div containers all mesh together in the wall. Use the following code to do this:

	jQuery( document ).ready( function( $ ) {
		$( '#container' ).masonry( { columnWidth: 220 } );
	} );

Conclusion

Masonry comes with a lot of built-in options that make it very appealing to use with WordPress. For example, you could apply the animation option to “animate” your post arrangements, append additional items to the wall (great for portfolio layouts), or incorporate it with Paul Irish’s Infinte Scroll. Regardless of how you plan to use the jQuery Masonry script, it’s a welcome addition to WordPress 3.5.

Side Note: Achieving this same effect in CSS3 is possible. However, you need to use the new “columns” functionality, which is not yet supported in every browser.
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • Paolo Sacchetti

    Nice post. Is it possible to set the width values of #container and .brick divs in % as well (for responsive behaviour)?

    • SarahlMorrow

      Yes, or you could define your max-width (I’d use ems) and then use media queries to achieve a more custom behavior based on screen size.

    • http://twitter.com/Tame_Geek Mark Thomson

      The documentation with Masonry gives a good indication on how to implement this with a responsive layout http://masonry.desandro.com/demos/fluid.html

  • http://twitter.com/zzramesses Corey Ellis

    Awesome! I didn’t know masonry was included w/ WP now.

  • http://twitter.com/ardennl Arden de Raaij

    ah how nice that Masonry is included. By the way, Isotope is awesome as well: http://isotope.metafizzy.co/ . It does require a license for commercial projects though!

  • Pingback: Tweet Parade (no.06 Feb 2013) | gonzoblog

  • http://twitter.com/maddisondesigns Anthony Hortin

    Great post Sarah. Like some of the others here, I wasn’t aware that Masonry was now included as part of core. Thanks!

  • http://www.facebook.com/derik.schneider Derik Schneider

    I’m integrating this into my WIP custom theme. I notice the more my long titles wrap in my bricks (I’m using panagrams for fake posts), that there is less space between the post below it, sometimes being overlapped by the proceeding post. Perhaps I should only use ‘content’ and no titles?

    Also, something I need to figure out, is why the next column starts at 440px instead of 240px.

    I’m glad this is integrated and thanks for sharing the code!

  • xmflsct

    Awesome! Thank you! This is the only tutorial that works perfectly.

  • http://twitter.com/BurakSahin59 Burak Şahin 

    like this >> http://xn--burakahin-42b.com/pin . I did it ;)

  • Theo Styles

    Any way of showing how the infinite scrolling works? I’ve tried it and its not working :S

  • http://www.gamemusiclife.com/ LainaLain

    I’ve tried pretty much all of the tutorials on how to do this and all of them have the same problem. People who are already familiar with jquery, html, and designing websites tend to think that everybody else knows all of that too. It’s probably clear as day how to install masonry into wordpress, but it’s not working for me. The instructions don’t even tell you which file to copy & paste half of this stuff into. The only one that was mentioned was the functions.php file. Then, the instructions say to implement the following HTML into the loop. Ok, well where is the loop exactly? In the header.php file? The index.php file? Should I post it in the section or the section? I’m sorry that I don’t already know everything there is to know about css stylesheets and coding like others. I tried to mimic everything the instructions did and it still doesn’t work. And I know it’s because I don’t which files and where in the files I’m supposed to type the codes in. And every each and one of these tutorials don’t even give out that kind of information. Is it just me, or the lack of a real tutorial?

    • http://wp.tutsplus.com/ Japh

      Hi LainaLain, sorry to hear you’ve found it so frustrating. It’s difficult to walk the line between giving enough information, but also not repeating the basics in every single tutorial.

      We have a lot of WordPress tutorials here on Wptuts+, many of them answer all the missing pieces you found going through this one (such as the loop). We even have one on creating a theme from scratch, every single step of the way.

      I hope you have more luck following one of those tutorials first.

      • http://www.gamemusiclife.com/ LainaLain

        All I’m trying to do is make a theme similar to Blogger’s Mosaic Dynamic View layout. And right now it seems impossible lol.

  • http://www.1000square.com/ Trevor C

    Great post! Not aware that WordPress included Masonry since version 3.5, http://codex.wordpress.org/Version_3.5. Thanks for sharing!

  • Pingback: Die besten meiner geteilten Links im Februar 2013 | pixelstrol.ch

  • Rami Saleem

    you made my day, really thank you, this article is worthier than $1000 …. :)

  • Pingback: Скрипт jQuery Masonry для оформления сайта в стиле Pinterest | Wordpresso

  • Julia

    “Step 3 Setup the Function” … where? Do I have to put that with in the header? And do I have to put around the part in functions php? Sorry for my surely stupid questions, I’m just trying to understand this jquery stuff somehow.

    • Ronburgundyy

      you normally want javascript or jquery to be in the footer as to not slow down the page loading

  • http://www.facebook.com/people/Jessica-Jenkins/1301100011 Jessica Jenkins

    None of this is explained well for beginners at all. Very confusing.

  • Ronburgundyy

    If anyone needs help i tried to explan it here:

    http://pastebin.com/y0D0NDSf

  • Livia Henderson

    Brilliant! i also had no idea Masonry was included in the latest version of WP.
    Are there any other cool tools that are included, that are hidden until activated?
    I would be very interested to know what other options, similar to this, are available in 3.5.
    Would be great to see an article that exposes all of the ‘cool sh*t’ that isn’t obvious, even to seasoned WordPress Users. A little WP pandoras’s box perhaps??
    thanks

  • Neil Robinson

    Excellent article, Sarah – but Ronburgundyy’s contribution clarified it superbly. I was struggling with it and didn’t realise I needed to enclose the script with () tags in my footer. His full code listing made it a no-brainer and it worked first time. Thanks guys!

  • Guest

    Solid tutorial, thanks! I’m trying to integrate this into a page, not a template. I’ve wrapped all my “bricks” appropriately with DIVs, added the scripts to functions.php and footer.php, added the CSS (wall width: 940; brick width: 450), and I’m just getting one column of 450px bricks, when it should be two side-by-side. Is there anything I need to change if it’s going into a page vs. a page template?