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() { ?> 
    <script>
    (function( $ ) {
        "use strict";
        $(function() {
            // set the container that Masonry will be inside of in a var
            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, {
                    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() { ?> 
    <script>
    (function( $ ) {
        "use strict";
        $(function() {
            var $grid = $('#ms-container');

            // Initialize Masonry
            $grid.masonry({
                itemSelector: '.grid-item'
            });

            /* When new items are loaded (e.g., via AJAX), 
               attach them to the container and tell Masonry 
               to recalculate their positions.
            */
            $grid.append(html).each(function(){
                $grid.masonry('reloadItems');
            });

            // Ensure layout triggers after images are fully loaded
            $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 responses to “How To Add Masonry Layout In WordPress”

  1. Daniel Aguirre Avatar

    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.

    1. Custom Fit Web Design Avatar

      I am glad you found my post helpful.

  2. Friso Avatar

    Hi, I just posted a comment but mistyped my emailaddress…
    Here’s the correct one..

  3. Friso Avatar

    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

    1. Custom Fit Web Design Avatar

      Hi Frisco,

      Please try changing the code to a new one – (see above UPDATED 10/28/22) .
      Let me know if it kept the masonry order from changing it after a reload.

      Andrea

    2. Friso Avatar

      Yes, that seems to work!
      Thanks so much!

  4. Yaya Avatar
    Yaya

    Thanks, works perfect for products list! (also with Divi & Woocommerce).

    1. Custom Fit Web Design Avatar

      I am glad my article helped you!