Injecting Ads into the Jetpack Carousel

This is really neat!

Kind words from VIP‘s rock star team after deploying our new ad integration extension to Jetpack’s Carousel. Built for, this extension appends a custom image to the full screen carousel modal. We’re excited to share it with the WordPress community, along with a few cautions and insights.

Rules are rules: no AdSense

If you were hoping to inject AdSense ads, we’re sorry to disappoint: AdSense policies clearly stipulate that an ad may not be “Displayed in pop-ups or pop-unders.” You may, of course, be able to leverage our approach for other, more forgiving ad networks. We envision the typical use case will involve an internal “house” ad image.

Hooking into Jetpack with JavaScript

Because the modal Jetpack Carousel is generated entirely by JavaScript, classic WordPress PHP API hooks do not apply. Fortunately, JetPack provides 2 JavaScript hooks: jp_carousel.afterOpen and jp_carousel.beforeClose. We hooked into afterOpen – which fires every time the carousel is generated – on line 14 of carousel-ads.js:

$( document.body ).on( 'jp_carousel.afterOpen', SELF.insertAd );

Defining parameters for the image

In order to make sure that our image is aligned correctly and responds with the rest of the carousel, we needed to add several data attributes to the container on line 79.

 var $ad = $( container).data('title', '')
.data('desc', '')
.data('caption', '')
.data('attachment-id', '')
.data('orig-size', '300, 250')
.data('comments-opened', 0)
.data('image-meta', '')
.data('medium-file', '')
.data('large-file', '')
.data('orig-file', '');

While these are mostly null attributes, the orig-size element is important for positioning inside the carousel.

Final thoughts

Features like the Jetpack Carousel, built almost entirely with JavaScript, are becoming increasingly common in the WordPress ecosystem. Understanding how to work with and hook into JavaScript is key. In addition to offering some practical tips for extending Jetpack Carousel, we hope this offers some insight into that future.

To see this code in action, hop on over to and check out any one of the carousels (like this one).

  1. […] that’s that. Get it here via GitHub! You an learn more about this via their announce post. Very clever and very thoughtful in terms of releasing it to the […]

  2. Hi Tanner, I hope you are fine. Nice work you did and it could help me a lot.

    I did not understand where is insert in my theme to start this, Can you help me?

  3. Actually, how to launch carousel-ads.php file, I’ve found just /www/wp-content/plugins/jetpack/modules/carousel/jetpack-carousel.php.

Leave a Comment

We make web publishing easy. Maybe even fun.

hire us apply