Detect if DFP ad units are on the page
To tell Google Tag Manager that DFP ad units are on the page, a variable will be set up which looks for DOM elements that need to be filled with ads. This variable uses a CSS selector to find these elements, and GTM will store the result in a variable which can be looked at later. To begin, open Google Tag Manager and log in, then select the relevant container. Once you're in GTM, follow the instructions to set up the variable.
- Choose Variables, then select New under User-Defined Variables at the bottom of the page.
- Give the variable a name (in this example, we'll use DFP Ads), then select DOM element as the type.
- Under Configure Variable choose CSS selector as the Selection Method and enter the following as the Element Selector:
div[id^="div-gpt-ad-"]
This looks for alldiv
elements on the page which have anid
beginningdiv-gpt-ad-
. Leave Attribute Name empty. - Make sure your variable looks like the following before continuing with this tutorial.
If you're interested in precisely what this does, here's the explanation: Google Tag Manager, once the DOM has loaded, looks through the DOM for all elements matching the CSS selector of div[id^="div-gpt-ad-"]
. This CSS selector is looking for all div
elements (which the DFP ad tags are, but so are other elements on the page) with an ID beginning with div-gpt-ad-
, which is true only for DFP ad tags, but is true for all DFP ad tags. Thus, the content of the variable is the concatenation of these elements. We'll use this variable to trigger the tag if and only if there are DFP ad units on the page which need DFP ads.
Trigger the DFP ad code
Using the variable we just set up, a trigger can be set up to trigger the DFP ad code (which we haven't got yet, but we'll get there).
- In Google Tag Manager, select Triggers → New.
- Set a name for the trigger (in this example, we'll use Page contains DFP Ads), and choose Page View as the event.
- For the trigger type…
- Page View: Don't use this option — DFP will not inject ads correctly with this selected.
- DOM Ready: Use this if you wish for the DFP ads to be injected as soon as possible.
- Window Loaded: Use this if you don't mind a short delay before the ads are injected in return for making sure that all the other elements of your page are loaded first.
- Under Fire On, select Some Page Views, then select your variable that you named earlier (in our case, DFP Ads). Choose does not equal and enter null into the box on the right.
You'll have to make some changes to the DFP ad code before you can add it though. Before you begin this section, open DoubleClick for Publishers and log in to your account. In this tutorial, we will use a DoubleClick for Publishers Small Business account, however this also works with DoubleClick for Publishers Premium accounts.
- In DoubleClick for Publishers, select Inventory → Generate tags. Under Select ad units, click Include all, then Generate Tags.
- Set the tag type to Google Publisher Tag, then click Continue. Leave the tag options to their defaults, and click Continue.
- Copy and keep the Document header section of the ad tags. You'll need to add this to the tag in Google Tag Manager. Ignore the Document body section of the ad tags.
Add the DoubleClick for Publishers ad tag code
It's time to add the ads from DFP.
- In Google Tag Manager, select Tags → New.
- Set a name for the tag (in this example, we'll use Google DFP). For the product, choose Custom HTML Tag.
- Paste in the DFP tag you copied in the previous section. We'll need to make some changes to this code though.
- Add the following code before the last closing
<script>
tag. This loops through all elements with an id beginning withdiv-gpt-ad-
and callsgoogletag.display(element)
on each element.var adunits = document.querySelectorAll('div[id^="div-gpt-ad-"]'); for (var i = 0; i < adunits.length; i++) { googletag.cmd.push(function() { googletag.display(adunits[i].getAttribute('id')); }); }
- Under Advanced Settings, set Tag firing options to Once per page. This ensures the code is not run multiple times per page.
- For Fire On, choose Some Pages, then check the trigger you named earlier (in this example, Page contains DFP Ads is the name of the trigger).
- Click Save Tag, then choose Publish in the top-right to publish this code to your site's GTM tag. Don't worry that you haven't implemented the ads yet — the code has no effect without the next section implemented.
Add the ad units to your HTML
You now need these div-gpt-ad-
elements on your page to tell the code above where to inject the ads. You shouldn't use the code from DFP, as mentioned earlier. Instead, you should take the ID from the tag in the previous section and use this as the id for the div element on your page.
Look in the tag code you added in GTM. You should see lines which look like this:
googletag.defineSlot('/122783354/BlogFooter', [728, 90], 'div-gpt-ad-1455876604709-0').addService(googletag.pubads());
Code language: JavaScript (javascript)
The string I have marked as bold is the id of the div you need to insert in your HTML for this ad unit. The div needs to be empty for this to work. Again, don't insert the Document body code provided by DFP into the div — use this instead.
<div id="div-gpt-ad-1455876604709-0"></div>
Code language: HTML, XML (xml)
DoubleClick for Publishers is now implemented using Google Tag Manager!
Any pages with DFP ad units should now load using Google Tag Manager! If you have any questions, let me know in the comments below. Here's an example ad implemented using the method discussed in this article.
i appreciated your article.
i beg your additional help related with my case.
1. i have whole 3 AD inventories.
2. but it depends on the number of paragraphs. sometime AD inventory is just 1, because it's too short.
3. so i should define the ad slot inconstantly.
4. if i define the whole slots and then loop sentence you made begin, the slot will be matched with only same div id?
5. or should i need to design the defineslot sentence inconstantly?
I hope your help.
Thank you!
Hi, I don't understand the part "Add the ad units to your HTML". I followed all the steps but still cannot see ads showing on the site.
Below is my tag in GTM, I've put the ad unit inside, but nothing happens, is that what you mean "Add the ad units to your HTML"? Or I should create a new tag and add the ad unit?
Have you added the div with the div-gpt-ad-* ID where you want the ad unit to show on your page?
Not yet, cause I am not sure where I should put this code below?
In the backend of the website or in GTM code?
div id="div-gpt-ad-1455876604709-0" /div
Place this on your site where you want the ad to appear. GTM will use the block of code you posted first to find this small tag and insert the ad inside it.
So you mean either way I still need to put the code myself via backend. Then why not just paste GAM code on the site instead? Is there any way I can just use GTM to put the code to the right place(for example, append, prepend...)?
You need to put just the small div tags where you want the ads to show. GTM still controls when and how the ads are delivered.
You can get GTM to place the tag anywhere and avoid having to add divs. The line
can be changed to select anything on the page. Select elements, append a new div with JavaScript, then display an ad in that newly added tag — all that is possible from GTM.
Hi! Tell me how to hide double click for publishers network code (Example 21762142461)
There is an example implementation of cancertherapyadvisor.com but I don't understand how to do it!
Perhaps through the google tag manager (Google Tag Manager)?
Or through this plugin /wp-content/plugins/hm-header-bidding-dfpapi/js/prebid.js
Direction where to go tell me!
does using google tag manager speed up the site then
Thank you for your help, but nothing worked
so thankful!!! worked correctly
Hi,
I'm having massive issues with the error googletag.defineSlot was called more times than there are DIVs in the DOM. Would disabling SRA fix this?
…thestaffcanteen.com
Thanks
Matt
How does this work when the code that is supposed to go in the is actually being inserted into the ? As far as I'm aware, GTM cannot insert script into the .
Are there any repercussions to doing it this way, putting all the code into the ?
It looks like you've used some HTML tags in your comment that have got stripped, I'm not really sure what you're trying to say?
does this work with var mapping ? If yes how to do it then please ?
Thank you for these steps. Most of this still worked once I was able to match up the steps based on the new GTM layout. However, I was not able to figure out what is meant by the last step. Are you saying this code should be added into my own website, replacing the numbers with my own digits? If so where - just at the start of the body on the page(s) we want the ads to show?
Hey, @grgarside:disqus ! I'm trying to setup GTM for my DFP Tags, I have the following head section for the DFP tags.
So I have to add at the end (almost at ) those lines:
Is that correct? Add it on GTM new Tag?
https://uploads.disquscdn.com/images/b221cd3ae6b7406c72614b06d0f582791754f765134dde96193ca736b41f36dc.png
Hey George,
Great Tutorial. I believe with the new GTM updates some things may have changed here. I wanted to see if you could test: https://trueverses.com/bible/kjv/verses/matthew-7-8?2017-06-02%20Show%20DFP%20Tags=experiment for me and see what might be going on? Dom elements look to be read but I can't get the top ad to fire. I used "ad-unit-" instead of "div-gpt-" for the variable. It shouldn't be an issue but I'm still waiting for the added
To be removed from my source code here so that I only have the div displayed. If those are removed do you believe this will work?
Hi George,
Firstly, thanks so much for this guide - your page is now a recommended resource by DFP support if you weren't aware 🙂 I've followed your instructions but am having a few issues with getting the scripts to execute in the right order through GTM and hoping you can provide some suggestions.
I've set up a test page with my ad units through GTM (https://goo.gl/eidfvR) and one without GTM/direct to the page (https://goo.gl/iRJXc7). Through GTM, I get "Exception when invoking function: Cannot read property 'getAttribute' of undefined" errors and 'Ad unit did not fetch' warnings in the GPT console.
I've tried both DOM Ready and Window Loaded trigger types with the same results. DFP support have suggested that the GPT functions are executing before their definition - any thoughts you may have would be really appreciated as there are not many resources around dedicated to this tagging method.
thanks!
I was not aware this was recommended by them, thanks for letting me know! Where about is this page mentioned exactly? I'd be interested in seeing the context.
With regard to your specific code, it seems to be most likely a timing issue. Manually running the injected script in the console after the page loads works well. The error regarding being unable to read the property indicates that
adunits[i]
is undefined, which is quite odd since if adunits itself was undefined then the for loop would not run.Perhaps try adding a delay to the tag in GTM, after the Window Loaded trigger. Since it works when running manually later, timing would seem to be the problem in my opinion. Also it seems like your JS has been minified, whether manually or automatically — perhaps try disabling this if you can to see if that makes a difference. Hopefully someone else will come to the rescue. Let me know if you fix it, I'm sure it will help others!
I'm getting the same 'getAttribute' undefined error. @disqus_jlDPFStRNy:disqus or @disqus_xzNAkrl5gg:disqus , did you manage to find a solution?
I'm getting the same error. I'm pretty familiar with GTM, but I don't know where to add the delay?
Help me with those erros, please:
gpt.js:4 Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.
Exception in queued GPT command TypeError: Cannot read property 'getAttribute' of undefined
https://uploads.disquscdn.com/images/649992923c2598d06fd8de5d25e92d1c7673987fdda05cf82381930aad2972d7.png
The issue is related to Javascript closures: http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example
The solution I found was to put the for loop INTO the anonymous function:
// Display ads
googletag.cmd.push(function() {
var adunits = document.querySelectorAll('div[id^="div-gpt-ad-"]');
for (var i = 0; i < adunits.length; i++) {
googletag.display(adunits[i].getAttribute('id'));
}
});
Hey Art thanks for replying with your fix I'm going to give this a go. Did you leave everything else the same here and just move up the loop into the start of the DFP header ?
It's been a while, but yes, I think so.
Anyway you could take a look here: https://trueverses.com/bible/kjv/verses/matthew-7-8?2017-06-02%20Show%20DFP%20Tags=experiment&google_force_console=1
I was able to get past that error but now it's saying my divs are not associated to an adunit. Any thoughts?
Adam, I actually put that code right before the the last closing
Hey Art,
Yup moved it just now but still getting "adunits failed to fetch". Can't seem to find a way past it.
Can you post the GTM code you're using and the id, dimensions, and ad path of one of your ads?
Sure can.
@artsupsiri:disqus any idea here?
Thanks for the solution, Art! It did the trick for me. Ads went up immediately.
Nice article.
I don't know if i did something wrong, but I wasn't able to set up on my page. I follow all the steps, but in the end, the google console (?googfc) is saying that the "ad unit failed to fetch". Do you have any toughts in what may be causing this error?
There's two reasons that this could occur:
If you have any DFP code on your site that isn't part of GTM, you are likely to cause this error. For example, you still have the JavaScript
googletagservices.com/tag/js/gpt.js
or any of the other code on your site. Make sure all DFP code is removed from the page itself so that Google Tag Manager runs the code and therefore is executed only once.If your ad code is too long, the request is blocked. You can fix this by removing the following line from the GTM tag:
You will get errors of "googletag.defineSlot was called without a matching googletag.display call" if you have more ad units in DFP than you inserted divs for on the page, but this is expected and completely fine.
Hi, Thanks for this post. Please can you clarify the this paragraph "The string I have marked as bold is the id of the div you need to insert in your HTML for this ad unit. The div needs to be empty for this to work. Again, don't insert the Document body code provided by DFP into the div — use this instead" . where i my to put this id. directly in the website ?
Yes, directly in the HTML of your page.
Hello
I may ask a silly question but why do you add DFP tags using GTM? Why is it better? Thanks!
It's useful because the ads can load last, prioritising other content. It's good for adding ads throughout your site, as GTM can be used to manage the ad tags globally, or even add the literal ad units to a page (a bit too far for this tutorial) without modifying the actual site code. GTM also allows for more precise control over when and how ads are loaded, including not loading the ad tag code if there are no ad units on the page, or loading ads when the user scrolls down, etc. There's far more flexibility with loading DFP using Google Tag Manager.
Hello George, thanks for this really helpful tutorial! I would need help exactly related to "even add the literal ad units to a page" based on URLs. Could you please help me? I tried your guide, but Im not able in loading the ads. Can you please help?
Use a GTM element selector to find where you'd like the ad inserted in your existing HTML, then use JavaScript to append the ad tag at this location. You can then run the rest of the code from the tutorial as usual as if you'd placed the HTML yourself. If you need any more help please let me know exactly which step you're having difficulty with.
Hi George, thanks for your kind reply!
I have this page http://www.mytestingsite.net/uncategorized/tag-manager-e-dfp/
Where I followed all your steps in this guide. But the banner does not appear.
After that, I'd like to show banners depending on the URL (so if the urls contain the word "pasta" then banners about pasta will show up). Can you help out? I can pay you for this as well! Your help will be really appreciated.
The last line of the JS script in your GTM tag reads
googletag.display(adunits[i])
however it should readgoogletag.display(adunits[i].getAttribute('id'))
. The banner then displays correctly for me.With regard to changing the code based on URL, I encourage you to look at Google Tag Manager Help's Tags, Triggers, and Variables page. Either use a different HTML tag with a different trigger or use variables to run the same trigger with different JS.
Thanks a lot ! In fact I am quite new in the tag's world !
Hello from Paris,
I follow each steps and I didn't succeed to deliver banners on my test page
Do you know if the recent modification in GTM have an impact on the set up you describe ?
I also remove the code
googletag.pubads().enableSingleRequest();
but I still have the following error in the google console
ad slots
"Ad unit failed to fetch."
page request
"Unknown div id in display(): undefined."
Here is the code I put in DFP with the piece of code you provide. Do you confirme that this is correct ?
and on my website I have just
Thanks in advance
This is a great approach , but for example , a wordpress based website with x number of categories or posts for different kind of banners, that are repeating constantly in the whole website, do you think changing :
div-gpt-ad-1455876604709-0 to div-gpt-ad-300x250 .
Would help ? or what you recommend?
Thanks for this
The ad ID means literally nothing apart from being the reference the code uses to link the div on the page to the code which inserts the ad. Providing these match, you can put any string and it will work fine. It's not read or interpreted, just used as a reference to link. Therefore, it doesn't matter what you put for the ID as it makes no difference to anything (as long as you change all instances of where the reference is called of course).
Thank you for providing useful tips.
I don't make sure "Add the ad units to your HTML" sentence.
Why should I use the div code insert in my html instead of DFP's code?
Because DFP's code will ignore all the work you've done in GTM. If you want GTM to manage your DFP tags, you need to use the HTML I provided in the post.
Great article, I was wondering if this also work with any other ad units beside DFP? Another question in the "Detect if DFP ad units are on the page" part where you configure the variable I only see "element selector" and "attribute name". Do I then insert as following:
- element selector = div
- attribute name = test
When i use this on the site?
Thanks in advance!
This should work with other ad units with some work on the HTML and JS.
Make sure you select ‘CSS selector’ as the Selection Method, ‘element selector’/‘attribute name’ is incorrect and won't work.
@grgarside:disqus Great and very useful article! Tks for sharing....Question, what if I use Tealium as a TMS? I can use the same div[id^="div-gpt-ad-"] as a JQuery Selector like CSS in GTM? I will be really gratefull if you can help me with this approach. Here's some info that might be helpful. http://www.lunametrics.com/blog/2016/08/24/tealium-vs-google-tag-manager/ PS: If you can email me will be awesome!!! Tks again @grgarside:disqus
George, I'm currently trying your implementation technique and cannot get any ads to show up. There should be a DFP delivered ad below the "Boost Your Bourbon IQ" house ad on this page: https://www.bourbonbanter.com/banter/join-us-for-the-2018-30daysofbourbon-challenge/
Not quite sure what I'm missing but if you have any ideas please let me know. Thanks!
Thank you for a great article George! I wanted to let you and others know that with a few minor modifications I was able to get this up and running on our site!
Work perfectly
var adunits = document.querySelectorAll('div[id^="div-gpt-ad-"]');
for (var i = 0; i < adunits.length; i++) {
var myad = adunits[i].getAttribute('id');
console.log('Ads : '+myad);
googletag.cmd.push(function(){googletag.display(myad);});
}
https://uploads.disquscdn.com/images/dfd240af6471ea755953d148f4345bec4cb1e6974fb06e80a0db24015e47ca6e.png