How To Add Masonry Layout In WordPress


Masonry is a JavaScript grid layout library based on columns. It works by placing elements in optimal position based on available vertical space. It doesn’t have fixed height rows.

Popular social site – Pinterest was the first major website to use this layout style.
As of WordPress version 3.9, Masonry is actually built into the core of WordPress ( wp-includes/js/masonry.min.js ). This WordPress version of Masonry also includes ImagesLoaded (imagesloaded.min.js).

masonry
  • When we fill a container with equally sized objects and float them left, we get a nice grid of images.
  • If we are displaying multiple images and they are all different sizes, they appear scattered.

LAYOUT BEFORE APPLYING MASONRY:

LAYOUT AFTER APPLYING MASONRY:

Markup for our HTML elements

<div class="row" id="ms-container">
  <div class="grid-item">...</div>
  <div class="grid-item">...</div>
  <div class="grid-item">...</div>
</div>

We need to tell WordPress to pull Masonry out of the core install and actually use it. This is done by enqueuing it in the functions.php file of your theme.

function my_masonry() {
	wp_enqueue_script('masonry');
}
add_action('wp_enqueue_scripts', 'my_masonry');


function MasonOnLoad() { ?> 	<!-- add masonry setting to the footer -->
  <script>
	(function( $ ) {
		"use strict";
		$(function() {
    			// set the container that Masonry will be inside of in a var
    			// adjust to match your own wrapper/container class/id name
   		 	var container = document.querySelector( '#ms-container' );
    			//create empty var msnry
    			var msnry;
   		 	// initialize Masonry after all images have loaded
    			imagesLoaded( container, function() {
        			msnry = new Masonry( container, {
            		// adjust to match your own block wrapper/container class/id name
            		itemSelector: '.grid-item'
        			});
    			});
		});
	}(jQuery));
  </script>
<?php } // end function MasonOnLoad
add_action('wp_footer', 'MasonOnLoad'); 

UPDATED 10/28/22

Another way to add masonry

NOTE: Masonry / imagesLoaded : prevent layout refresh from moving already loaded items

function MasonOnLoad() { ?> <!-- add masonry setting to the footer -->

<script>
 
	(function( $ ) {
    		"use strict";
		$(function() {
    
    		var $grid = $('#ms-container');
    		// init Masonry
    			$grid.masonry({
        		// options
        			itemSelector: '.grid-item'
    			});
    
    //Here I attach the new loaded items (html var) in the #ms-container div.
    $grid.append(html).each(function(){                              
        $grid.masonry('reloadItems');
    });         

    $grid.imagesLoaded(function(){
        $grid.masonry();
    }); 
});
}(jQuery));

</script>

<?php } // end function MasonOnLoad
add_action('wp_footer', 'MasonOnLoad'); 

As long as we have a width set on our container div, the code above performs the magic we need it to and reflows the elements. If you set the div width to a percent, Masonry automatically reflows the items as the page resizes and maintains their aspect ratio.

18 comments:

  1. Great plugin.

    I was wrestling with Macy.j masonry layout for a long time and never got it to work.
    I tried multiple threads.

    Found your thread and everything worked first try, kudos on a well explained post.

    I feels this is better than macy.js because this technique uses an existing masonry js file in the core wordpress system.
    No extra files and updates from github required.

  2. Hello,
    I am using the script on my WordPress website on this page https://heidinga-saxophone-necks.com/the-players/
    Thanks for making it available! It works great. There is one small thing however. Sometimes the order of the Div’s changes, after a reload the sort well again. For most this is not important but since made borders around the Div’s except for the outer one for me it is…
    Any idea how ensure that the Mansory order is always the same?
    Thanks!
    Friso

Leave a Reply

Your email address will not be published. Required fields are marked *