Masonry style WordPress Gallery without using plugin

Nowadays Masonry styled Gallery layouts are very common for websites. There are many third party WordPress plugins for Galleries that either provide their own Gallery or provide styling skins for the default WordPress Gallery.

For the sake of this post we will learn how to apply Masonry Layout to default WordPress Gallery. Below is the code.

CSS

.gallery-columns-0 .gallery-item {
    width: 100%;
}
.gallery-columns-1 .gallery-item {
    width: 100%;
}
.gallery-columns-2 .gallery-item {
	width: 50%;
}
.gallery-columns-3 .gallery-item {
    width: 33.33%;
}
.gallery-columns-4 .gallery-item {
	width: 25%;
}
.gallery-columns-5 .gallery-item {
    width: 20%;
}
.gallery .gallery-item {
	text-align: center;
	float: left;
	padding: 0 15px;
	margin-bottom: 30px;
}

@media all and (max-width:680px) {
	
.gallery-columns-2 .gallery-item,
.gallery-columns-3 .gallery-item,
.gallery-columns-4 .gallery-item,
.gallery-columns-5 .gallery-item {
	width: 100%;
	padding-right: 0;
}

}

JQuery

var galleries = jQuery(".moods-masonry-gal>.gallery");
if (galleries.length) {
	galleries.each(function(){
		var current = jQuery(this);
		var gal_id = jQuery(this).attr('id');
		current.imagesLoaded( function() {
			current.masonry();
		});
	});
}

PHP

function masonry_scripts() {
	wp_enqueue_script( 'masonry', get_template_directory_uri() . '/js/masonry.pkgd.min.js', array('images-loaded'), '1.0.0', true );
    wp_enqueue_script( 'images-loaded', get_template_directory_uri() . '/js/imagesloaded.pkgd.min.js', array('jquery'), '1.0.0', true );
}
add_action( 'wp_enqueue_scripts', 'masonry_scripts' );

Note that masonry.pkgd.min.js and imagesloaded.pkgd.min.js should be present in js folder of your active theme.

Join the discussion

  1. Avatar
    Konstantin says:

    JQuery code Where to insert?

Leave a Reply

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