Envira Gallery Blog

Digital Photography Tips, Tutorials and Resources

how-to-create-a-masonry-pinterest-like-layout-in-wordpress

How to Create a Masonry Layout in WordPress

by Waseem Abbas on Oct 13, 2016

Do you want to display your blog posts as a Pinterest like grid? A masonry layout is a great way to display your posts, especially when you want to show off your beautiful photography. In this article, we will share how to create a masonry layout in WordPress.

A masonry layout is a Pinterest like grid that displays your posts in vertical columns. It is especially perfect if you are a photographer, or if you have a lot of portrait-oriented featured thumbnails.

To create a masonry, Pinterest like layout in WordPress, you’ll need to follow these 5 steps:

  • Step 0. Load the Masonry Library to your site
  • Step 1. Add the JavaScript to your site’s footer
  • Step 2. Create a new template file for your masonry loop
  • Step 3. Add the masonry loop to your theme
  • Step 4. Specify the width for your masonry layout
  • Step 5. Optimize your masonry layout for mobile devices

By the end of this tutorial, you will be able to display your posts as a masonry grid that looks something like this:

Masonry Grid in WordPress

Note: You can use Envira Gallery to create a Masonry Gallery Layout without writing any code. See Masonry Gallery Demo // Get Started with Envira Gallery

Ready to get started? Let’s go!

Step 0: Load the Masonry Library to Your Site

If you are using WordPress 3.9 or above, then it already includes the latest version of the Masonry Library.

We highly recommend that you keep your WordPress updated to the latest version, however, if for some reason you are using an older version of WordPress then you’ll need to load the Masonry Library to your site.

Simply copy and paste the following code into your theme’s function.php file:


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

(For more help with this step, check out this guide on how to properly add JavaScripts and Styles in WordPress.)

Step 1: Add the JavaScript to Your Site’s Footer

Next, you’ll need to copy and paste the following JavaScript into your site’s footer:


if ( ! function_exists( 'slug_masonry_init' )) :
function slug_masonry_init() { ?>
<script>
    //set the container that Masonry will be inside of in a var
    var container = document.querySelector('#masonry-loop');
    //create empty var msnry
    var msnry;
    // initialize Masonry after all images have loaded
    imagesLoaded( container, function() {
        msnry = new Masonry( container, {
            itemSelector: '.masonry-entry'
        });
    });
</script>
<?php }
//add to wp_footer
add_action( 'wp_footer', 'slug_masonry_init' );
endif; // ! slug_masonry_init exists

This will initialize the masonry layout, calculate the size of all your posts, and then create the columns for your blog posts.

Step 2: Create a New Template File for Masonry Loop

In this next step, you’ll need to add a new template file into your theme and name it content-masonry.php.

Copy and paste the following code into this new file:


<article class="masonry-entry" id="post-<?php the_ID(); ?>" <?php post_class(); ?> >
<?php if ( has_post_thumbnail() ) : ?>
    <div class="masonry-thumbnail">
        <a href="<?php the_permalink(' ') ?>" title="<?php the_title(); ?>"><?php the_post_thumbnail('masonry-thumb'); ?></a>
    </div><!--.masonry-thumbnail-->
<?php endif; ?>
    <div class="masonry-details">
        <h5><a href="<?php the_permalink(' ') ?>" title="<?php the_title(); ?>"><span class="masonry-post-title"> <?php the_title(); ?></span></a></h5>
        <div class="masonry-post-excerpt">
            <?php the_excerpt(); ?>
        </div><!--.masonry-post-excerpt-->
    </div><!--/.masonry-entry-details -->  
</article><!--/.masonry-entry-->

Step 3: Add the Masonry Loop to Your Theme

Next, you’ll need to add the masonry loop to your theme’s index.php file.

Here’s an example of what the Twenty Sixteen theme’s index.php file looks like before we add in the masonry loop:


          <?php if ( have_posts() ) : ?>

			<?php if ( is_home() && ! is_front_page() ) : ?>
				<header>
					<h1 class="page-title screen-reader-text"><?php single_post_title(); ?></h1>
				</header>
			<?php endif; ?>

			<?php
			// Start the loop.
			while ( have_posts() ) : the_post();

				get_template_part( 'template-parts/content', get_post_format() );

			// End the loop.
			endwhile;

			the_posts_pagination( array(
				'prev_text'          => __( 'Previous page', 'twentysixteen' ),
				'next_text'          => __( 'Next page', 'twentysixteen' ),
				'before_page_number' => '<span class="meta-nav screen-reader-text">' . __( 'Page', 'twentysixteen' ) . ' </span>',
			) );

			get_template_part( 'template-parts/content', 'none' );

		endif;
		?>

To add the masonry loop, add a div with the id masonry-loop around while ( have_posts() ). Then, replace get_post_format() with 'masonry' as shown below:


          <?php if ( have_posts() ) : ?>

			<?php if ( is_home() && ! is_front_page() ) : ?>
				<header>
					<h1 class="page-title screen-reader-text"><?php single_post_title(); ?></h1>
				</header>
			<?php endif; ?>
                        <div id="masonry-loop">
			<?php
			// Start the loop.
			while ( have_posts() ) : the_post();

				get_template_part( 'template-parts/content', 'masonry' );

			// End the loop.
			endwhile;
                        </div><!--/#masonry-loop-->
			the_posts_pagination( array(
				'prev_text'          => __( 'Previous page', 'twentysixteen' ),
				'next_text'          => __( 'Next page', 'twentysixteen' ),
				'before_page_number' => '<span class="meta-nav screen-reader-text">' . __( 'Page', 'twentysixteen' ) . ' </span>',
			) );

			get_template_part( 'template-parts/content', 'none' );

		endif;
		?>

You can apply this loop to any template file that displays posts, such as archives, categories, etc.

Step 4: Specify the Width for Your Masonry Layout

We recommend specifying the width for your masonry layout as a percentage. To calculate this percentage, you’ll need to divide 100% by the number of posts (columns) you want to display per row.

For example, if you want to display 5 posts per row, then you would modify your theme’s style.css file as follows:


.masonry-entry{width:20%}

 

Step 5: Optimize Your Masonry Layout for Mobile Devices

Now your masonry grid should look good on desktops, however, you should also optimize your masonry layout for mobile devices.

To do this, you’ll need to add some code to your theme’s template files. We are using the Mobble plugin to help with this.

In your theme’s function.php, copy and paste the following code:


if (! function_exists('slug_custom_excerpt_length') ) :
function slug_custom_excerpt_length( $length ) {
    //set the shorter length once
    $short = 10;
    //set long length once
    $long = 55;
    //if we can only set short excerpt for phones, else short for all mobile devices
    if (function_exists( 'is_phone') {
        if ( is_phone() ) {
            return $short;
        }
        else {
            return $long;
        }        
    }
    else {
        if ( wp_is_mobile() ) {
            return $short;
        }
        else {
            return $long;
        }
    }
}
add_filter( 'excerpt_length', 'slug_custom_excerpt_length', 999 );
endif; // ! slug_custom_excerpt_length exists

Next, edit your content-masonry.php file and add the following code:


<article class="masonry-entry" id="post-<?php the_ID(); ?>" <?php post_class(); ?> >
<?php if ( has_post_thumbnail() ) : ?>
    <div class="masonry-thumbnail">
        <a href="<?php the_permalink(' ') ?>" title="<?php the_title(); ?>"><?php the_post_thumbnail('masonry-thumb'); ?></a>
    </div><!--.masonry-thumbnail-->
<?php endif; ?>
    <div class="masonry-details">
        <h5><a href="<?php the_permalink(' ') ?>" title="<?php the_title(); ?>"><span class="masonry-post-title"> <?php the_title(); ?></span></a></h5>
        <?php 
            //put the excerpt markup in variable so we don't have to repeat it multiple times.
            $excerpt = '<div class="masonry-post-excerpt">';
            $excerpt .= the_excerpt();
            $excerpt .= '</div><!--.masonry-post-excerpt-->';
//if we can only skip for phones, else skip for all mobile devices
            if (function_exists( 'is_phone') {
                if ( ! is_phone() ) {
                    echo $excerpt;
                }
            }
            else {
                if ( ! wp_is_mobile() ) {
                    echo $excerpt;
                }
            }
        ?>
    </div><!--/.masonry-entry-details -->  
</article><!--/.masonry-entry-->

To set the width of our masonry layout for mobile devices, we’ll use an external stylesheet named masonry.css, and then run the following code to execute it:


if ( ! function_exists ( 'slug_masonry_styles' ) ) :
function slug_masonry_styles() {
    //set the wide width
    $wide = '25%';
    //set narrow width
    $narrow = '50%';
    /**Determine value for $width**/
    //if we can only set narrow for phones, else narrow for all mobile devices
    if (function_exists( 'is_phone') {
        if ( is_phone() ) {
            $width = $narrow;
        }
        else {
            $width = $wide;
        }        
    }
    else {
        if ( wp_is_mobile() ) {
            $width = $narrow;
        }
        else {
            $width = $wide;
        }
    }
    /**Output CSS for .masonry-entry with proper width**/
    $custom_css = ".masonry-entry{width: {$width};}";
    //You must use the handle of an already enqueued stylesheet here.
    wp_add_inline_style( 'masonry', $custom_css );
}
add_action( 'wp_enqueue_scripts', 'slug_masonry_styles' );
endif; // ! slug_masonry_styles exists

If you are using the masonry layout on your index and archives pages, then you can simply use the following code:


if ( is_home() || is_archive() ) {
    add_action( 'wp_enqueue_scripts', 'slug_scripts_masonry' );
}

That’s it! We hope this article has helped you to learn how to create a masonry, Pinterest like layout in WordPress. You may also want to check out our guide on how to create a masonry image gallery.

If you like this article, then please follow us on Facebook and Twitter for more free WordPress tutorials.

Comments

    1. Hey Arun. As explained in Step 1, it will initialize the masonry layout, calculate the size and create columns for the images. 🙂

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.