A masonry layout is a great way to display images in a beautiful grid, even when they have different sizes. It is very common among photography blogs to use a theme that has this feature. You can see some examples on the Masonry page.
However nice it looks, including ads into a masonry grid is not as easy as it might sound. I got asked for a solution a lot and finally had the chance to dig a bit deeper and come up with a way how to solve this with Advanced Ads.
Why don’t ads properly display in a masonry grid?
Masonry layouts are normally implemented using a JavaScript library. One of the most common libraries for this is Masonry by David DeSandro. It is also included in WordPress already and developers only need to activate it.
The way this and other scripts are working is that they take a set of containers, get their sizes, and then reorder them dynamically. All considered elements need to have the same selector. If one of them, like the ad container, does not have this selector – normally in form of a class – it is not considered in the grid and either displays completely outside the grid or is hidden beneath it.
How to consider ads in a masonry layout?
Based on the explanation above, adding an ad to the layout is actually rather simple.
You only need to find out which selector is used in the theme to find all elements that need to be considered. In a recent example, it was just a list of posts and the class each post container had was recent-post.
I then just took this class and added it to the ad container. The option for this can be found on the ad edit screen in the Layout / Output meta box. Simply add the class name to it like on the image below.
In order to find the correct class, you need to ask the theme developer or take a look into the theme’s source code where the masonry script is initialized. For the Masonry script it might look like this:
$('.grid').masonry({ itemSelector: '.recent-post', columnWidth: 200 });
Adding the ad to the page with the masonry layout is another question. If this is a list of posts, you can use the Post Lists placement or you can use the PHP function to include it into your theme manually.
Solution for Isotope
Isotope is an extension of the mentioned Masonry script. You can use the appended
or insert
methods as described here to add elements to it. This is a simplified example from one of our users:
var tbp_posts = jQuery( '.tbp_masonry' )[0];
var ad = jQuery( '<article class="post">AD CONTENT</article>' ).appendTo( tbp_posts );
var iso = Isotope.data( tbp_posts );
iso.appended( ad );
Code language: JavaScript (javascript)
In line two, you can also pick the Advanced Ads placeholder container from your HTML and wrap it in the <article class="post">
tag.