WP Rocket is one of the most popular caching plugins for WordPress, offering a rich set of features and flexibility.
WP Rocket has the ability to combine and minify JavaScript and CSS, generating a separate file for each. Additionally, it collects all inline JS/CSS from the site's HTML code and adds it to the aggregated cached files. This is certainly convenient, but in some cases — especially when used alongside other plugins — it can lead to errors or improper behavior.
The task mentioned in this article’s title might seem a bit odd. Why cache ads at all? Why not just leave them as they are and render them where needed? That’s a fair point! But what if you decide to use caching together with the Flat PM plugin?
Flat PM is an ad management plugin. It allows you to easily manage all ads on your site with advanced display conditions.
And here’s the issue — WP Rocket and Flat PM don’t seem to get along. I suspect that at some point everything worked fine, until the developers of Flat PM decided to shift their ad injection logic from HTML regular expressions (not confirmed) to JavaScript and DOM manipulation. As a result, Google Ads stopped being cached correctly, and ads stopped appearing on the site.
Fortunately, the fix is quite simple. You can either dig into the WP Rocket plugin code or reach out to their support. The second option is much easier — there are a lot of files in Rocket, and their support team is responsive and always willing to help.
WP Rocket extends its functionality using a set of filters and hooks that allow you to modify its caching logic. In our case, we’ll use the rocket_excluded_inline_js_content filter, which accepts an array of keys — any inline JS content matching those keys will be excluded from the aggregated cache file.
add_filter('rocket_excluded_inline_js_content', function($excluded_inline) {
if(($delete_key = array_search('adsbygoogle', $excluded_inline)) !== false)
{
unset($excluded_inline[$delete_key]);
}
return $excluded_inline;
}, 10, 1);In the code above, we’re searching the array for adsbygoogle. This key is responsible for ignoring AdSense inline JS within the HTML. If we find it in the $excluded_inline array, we remove it and return the updated array. Now, WP Rocket will no longer skip those ad blocks — it will cache them like any other JavaScript.
As a result, Flat PM will now correctly display Google ads.
