Create a Masonry Layout on the Home/Blog Page in WordPress

WordPress already comes with Masonry either as pure Javascript or a jQuery plugin, here is how you can style a home blog page in a Masonry format with 3 columns.

wordpress-masonry-layout

Enqueue the built in WordPress jQuery Masonry script and create a initiate file which targets our .home .entry posts.

<?php
//Masonry load scripts
function wpb_masonry_scripts_styles() {
wp_enqueue_script ( 'jquery-masonry');
wp_enqueue_script ( 'masonry-init' , get_stylesheet_directory_uri() . '/js/masonry-init.js', array('jquery-masonry'), '1', true );
}
add_action( 'wp_enqueue_scripts', 'wpb_masonry_scripts_styles' );
view raw masonry-scripts.php hosted with ❤ by GitHub
// Settings Masonary
jQuery( document ).ready( function( $ ) {
$( '.content' ).masonry( );//targets the posts container
} );
view raw masonry-init.js hosted with ❤ by GitHub

 

Add some CSS style for the posts, here I am setting full width on smaller devices below 768px

.home .entry {
background: #f8f9fa;
margin: 0 1.5% 30px !important;
padding: 3%;
width: 100%;
}
/* 3 Up on devices ipad portrait plus */
@media only screen and (min-width: 768px) {
.home .entry {
width: 30%;
}
}
view raw masonry.css hosted with ❤ by GitHub

 

The pagination is an issue in Genesis as it is also masonified (don’t know if that is a legit term) because it shares the same container as the posts – here is a jQuery/CSS hack on that.

//shift pagination out of container
jQuery(function( $ ){
$('.archive-pagination').insertAfter(".content-sidebar-wrap");
});
//ref- http://api.jquery.com/insertafter/
/*override masonry*/
.archive-pagination {
position: relative !important;
top: 0 !important;
}

Loading via javascript

You can also load via javascript only method which negates the need for jQuery

<?php
//Masonry load scripts
function wpb_masonry_scripts_styles_alt() {
wp_enqueue_script ( 'masonry'); //jqueryless
}
add_action( 'wp_enqueue_scripts', 'wpb_masonry_scripts_styles_alt' );
//Masonry Style javascript
function wpb_js_masonry() { ?>
<script>
var container = document.querySelector('.home .content'); //set container
var msnry;
// initialize Masonry after all images have loaded
imagesLoaded( container, function() {
msnry = new Masonry( container, {
itemSelector: '.entry', //set target
});
});</script>
<?php
}
add_action( 'wp_footer','wpb_js_masonry', 20);//add priority to push it below masonry script

Leave a Comment





%d bloggers like this: