This is a guest post by Josh Pollock
The Pinterest-like grid display of posts has been a popular design for WordPress blog index pages for a while. It is popular not only because it mimics the look of the popular social media site, but also because it makes the best use of space on the screen. On a WordPress blog index, it allows each post preview to be the size it naturally needs to be, without leaving extra space.
In this tutorial, I will show you how to use the popular Masonry JavaScript Library to create cascading grid layouts for your blog index, as well as archive pages for your theme. I will address a few issues that you need to consider for mobile-optimization and how to solve them.
Note: This is an advanced level tutorial for those who feel comfortable editing WordPress themes and have sufficient HTML/CSS knowledge.
Step 1: Add Necessary Libraries To Your Theme
Update: WordPress 3.9 now includes the latest version of Masonry.
First you need to load Masonry into your theme, using this code:
if (! function_exists(‘slug_scripts_masonry’) ) :
if ( ! is_admin() ) :
function slug_scripts_masonry() {
wp_enqueue_script(‘masonry’);
wp_enqueue_style(‘masonry’, get_template_directory_uri().’/css/’);
}
add_action( ‘wp_enqueue_scripts’, ‘slug_scripts_masonry’ );
endif; //! is_admin()
endif; //! slug_scripts_masonry exists
This code simply loads masonry and makes it available to your theme’s template files (see our guide on how to properly add JavaScripts and Styles in WordPress). Also note that we are not adding jQuery as a dependency for either. One of the advantages of Masonry 3 is that it does not require jQuery, but can be used with it. In my experience, initializing Masonry without jQuery is more reliable, and opens up the possibility of skipping loading jQuery, which can help with both page load times and compatibility issues.
Step 2: Initialize The Javascript
This next function sets up Masonry, defines the containers that will be used with it and also makes sure everything happens in the right order. Masonry needs to do calculate the size of each of the items on the page in order to layout its grid dynamically. A problem I’ve run into with Masonry in many browsers is that Masonry will miscalculate the height of items with slow loading images, leading to overlapping items. The solution is to use imagesLoaded to prevent Masonry from calculating the layout until all images are loaded. This ensures proper sizing.
This is the function and action that will output the initialization script in the page footer:
if ( ! function_exists( ‘slug_masonry_init’ )) :
function slug_masonry_init() { ?>
>