Did you know that jQuery Masonry script comes in-built with WordPress? We just need to enqueue to use it. In this article I explain the steps to implement jQuery Masonry script to display Posts in Posts page and archives similar to Pinterest.
Note: I have tested this in Genesis Sample child theme and the process should work in any other Genesis child theme with minor adjustments.
Set excerpts to be shown
At Genesis > Theme Settings > Content Archives select Display post excerpts.
Prepare for jQuery Masonry initialization
Place the following in a file named say, masonry-init.js under js (create, if it does not exist) directory in active theme:
|1 2 3 4 5 6 7 8 9 10 11|
In the above we are specifying .content div as the masonry container and .entry as each masonry brick. gutterWidth is the value in pixels of the horizontal gap between the Post blocks.
[Optional] Infinite Scroll
If you would like next set of Posts to load automatically as the visitor scrolls down, download jquery.infinitescroll.min.js from here. Upload it to /js directory under the child theme. Also create a file named say, infinitescroll-init.js under child theme’s /js having this code:
|1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28|
In the above the only value that may want to change is the URL of loading indicator image, loader.gif. Download it, upload to your server and use that URL.
Enqueue the scripts and set up the layout
Add this in child theme’s functions.php:
If you do not wish to use Infinite scroll, comment out or delete the two enqueue lines under //* Infinite Scroll.
add_image_size( 'masonry-brick-image', 255, 0, TRUE );
change 255 to width of each post (which is dependent on how many columns you want in the available space).
Here’s the formula to calculate the width of each post:
((no. of columns) * x) + ((no. of columns – 1) * gutter width) = “.site-inner” width
Ex.: Let’s say you want 4 columns and you’ve set the gutter width to 40px and the available space of .site-inner div is 1140px (can be obtained from Firebug), then
4x + (3*40) = 1140
i.e., x = (1140 – 120)/4 = 255.
Note: This step is not mandatory. If 0 is entered when defining the “masonry-brick-image” custom image size handle, full width of the image will be used. The benefit of setting the post thumbnail image width to only how much is actually needed (that is the container in which it is shown) is faster page loading time due to decreased image file sizes.
Add the styling
Add the following sample CSS code at the end of child theme’s style.css and adjust to suit:
Set the width of .masonry-page .content .entry to width of each post as calculated from the formula earlier.
Install activate and run Regenerate Thumbnails.