I have struggled to setup Google Auto Ads in Discourse due to lack of proper guide anywhere. Finally, I’ve become successful in setting up Google Auto Ads in Discourse.
Google is giving a simple one line script to setup the Auto Ads, but Discourse’s way of handling external scripts is different. The moment the page reloads, the Auto Ads are gone.
The ideal way to setup the Auto Ads is as follows:
First step to do is, allow Google Adsense to work. By default, Discourse blocks all external scripts. So, go to your Discourse Admin > Settings. Search for “content security policy” and enable the features as shown in the below image. Enable CSP and add “https:” and “unsafe-inline”. This will enable any external script that you installed with a ‘https’ will not be blocked by Discourse.
Though we can setup the auto ads script in ‘< /head>’ of theme section, the same won’t work on refresh. So, we can setup Google Ads using "Google Tag Manager. The steps are as under.
Login to Google Tag Manager: https://tagmanager.google.com/. Crete an account and after creating, it will display two codes to place before < /head> and < /body>. Copy paste them in Discourse Admin > Customize > Themes > Edit CSS/HTML and paste in head and body sections respectively.
Now, Choose Workspace and Create a new user defined variable and call it “asClientID” (without quotes), as shown in the below image:
- Configure the variable as a Constant. The value to enter is your AdSense Client ID.
- Click on Tags on the left side of the screen within your GTM workspace and Create a new Tag called “AS - Page view - ALL”.
- Tag Type: Custom HTML
- Copy this code to HTML:
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
Triggering - choose All Pages
Preview and Publish.
Copy the GTM ID:
- In Discourse Admin > Settings > Search GTM and paste GTM ID, confirm.
- Save & that’s it. Go to your Discourse site & refresh the page, so that your Auto Ads starts displaying.
Further, I also advise you to install the official discourse-adplugin and setup the ad codes (IDs) in Admin > Settings > Adsense, just in case if auto ads doesn’t work due to any reason, these slot based ads will work.
Any doubts? Feel free to ask below.