How to Target DFP Ads to Specific URLs

Recently I had an advertiser running a direct campaign that wasn’t having great success. We decided if we could match the ad to specific pages, the results might be better.

Unfortunately, like many things in Google DFP – this was going to be complex to set-up. I got it working in the end, and the campaign had almost double the click through.

Why Target Specific URLs?

By default, when a line item is assigned to an ad unit, this will appear across the whole site (run of site). As most sites are based on templates or themes, the ad tags will be on every page (such as in a sidebar or header).

In some sites we may have ad units only serving on certain categories of page (such as a blog post, or a product page, etc).

But what if you want more fine-grained control, and hand-pick the pages the ad will appear on? This is called custom criteria, and it’s a bit of a pig to set-up.

Here’s how to do it:

1. Setup Targeting Criteria on Your Website

We need an extra line of Javascript in the tagging code. There are some examples here.

In this case we are setting criteria for the entire page (not an individual ad slot). We call a method called .setTargeting, assigning a key (I’ve called it “url”), and a value (the URL of the page).

googletag.defineSlot("/1234/travel/asia/food", [300, 250], "div-gpt-ad-123456789-1.addService(googletag.pubads());
// New line here
// Before this line here

It depends on your individual site as to how you come up with the URL name. I’m using WordPress, so this is what I do on a post.

In the header.php (where I setup the DFP ad slots) I’ve added some extra PHP. This is inside the Javascript. The PHP is parsed on the server and outputs the URL into the Javascript line.

$url = parse_url(get_permalink($post_id));
$targeturl = substr($url['path'],0,40);

googletag.pubads().setTargeting("url","<?php  echo  $targeturl ?>");

Unfortunately DFP restricts criteria value to 40 characters, so the PHP code here will remove the hostname, and restrict to 40 characters. So if you have a massive URL, this is what will get generated.

If your URL is

The code will look like this:


This is just a limitation of DFP, so if you have massive URLs you may not be able have as fine-grained control as you wish.

2. Targeting Your DFP Line Item

First we need to setup the new custom targeting key:


  1. Open up DFP in your browser.
  2. Navigate to the Inventory tab.
  3. Select Custom Targeting, and click New Key.
  4. Name should be url, then click Add values.
  5. Into the box you can enter a large list of URLs and Apply.
  6. Then click Save.

Then assign the keys and values to the line item targeting:

  1. Go to your Line Item settings, and scroll down to Add targeting.
  2. Click on Custom criteria, then Add key.
  3. Type in url (the criteria key name you already setup in inventory).
  4. You can then quickly go through and check each URL you want to target (you can also free-form enter additional URLs).
  5. Make sure ALL URLs you want to target are entered into the single entry. Don’t add a new key record for each URL or else DFP will try to AND them together.


That’s it!

In order to test this, I had a dummy order and line item, and targeted them to an ad slot on a local developer site.  I was then able to check the ad was only appearing on the URLs chosen.

The very stupid thing I did was to not stop this dummy campaign, and because I had the same ad slot on a live site – I served dummy ads on the live site for a few days. Oops.


Hi, I'm James, and for the last decade I've made a living by making my own blogs and websites.
Updated: September 14, 2016


  1. Hi there is a way to hide line item in all url that contain a word in a url for example i want target line item where in the url thereisn’t a word House?
    Thanks a lot

  2. I need help with .setTargeting. Basically, I have 3 responsive ad_units which runs in all pages.

    Now I need to have roadblock ads for some posts. That means I only want to run specific Line Items with the key-value of “roadblock==ctm”. I already added my key-value pair in my dfp inventory (key:”roadblock”, value=”ctm”), and matched it into the Line-Item, but still all the other banners are showing up when i tested it…please help me.

  3. Thanks for this guide – one question I have is how do I target the homepage (I’m not on WordPress).

    I’ve tried just / and that hasn’t worked – any ideas?

    • Maybe in your template for the home page you could the URL value that is passed to DFP to something unique, like /#home for example.

      • Thanks James – much appreciated.

        It seems so odd that DFP wouldn’t have something in place without requiring this?

        Is there any way you can use another key value in a way that doesn’t involve jumping into code?

  4. Hi James,

    this has been helpful, however I am still bit confused. I set up the tags as below. However I’m not sure what to put after .setTargeting(‘url’, []); within the [] as if i want this to be free form at the time of setting up line item so i can change it depending on the campaigns sold. I did try ‘window.parent.location’ but that didn’t work for me. How can I make this work as i desperately need to start targeting to specific article pages such as technology/the-power-of-non-de

    Thank you,

    Document header

    Widgets Magazine

    var googletag = googletag || {};
    googletag.cmd = googletag.cmd || [];

    googletag.cmd.push(function() {
    googletag.defineSlot(‘/269582516/SYN_desktop-tech-article_billboard_970x250’, [970, 250], ‘div-gpt-ad-1479294366337-0’).addService(googletag.pubads());
    googletag.defineSlot(‘/269582516/SYN_desktop-tech-article_DMPU_300x600’, [300, 600], ‘div-gpt-ad-1479294366337-1’).addService(googletag.pubads());
    googletag.defineSlot(‘/269582516/SYN_desktop-tech-article_leaderboard2_728x90’, [728, 90], ‘div-gpt-ad-1479294366337-2’).addService(googletag.pubads());
    googletag.defineSlot(‘/269582516/SYN_desktop-tech-article_MPU_300x250’, [300, 250], ‘div-gpt-ad-1479294366337-3’).addService(googletag.pubads());
    googletag.pubads().setTargeting(‘url’, []);

    • Gemma, you need to have code in your CMS to inject the URL. In my article above I describe how I did it in wordpress. You could probably do it in JavaScript by using window.location.pathname

      googletag.pubads().setTargeting(‘url’, window.location.pathname);

      You don’t need the square brackets.

      • Hi James,

        Thank you for this! I will change my code to just have the googletag.pubads().setTargeting(‘url’, window.location.pathname);

        is there any extra code i need to put into the javascript at all like you did with word press?


        • I’m not sure if DFP still has the 40 character limitation on URLs – so this could be a problem if you have long URLs.

          • Yes they do i’m thinking using tiny url would work though instead? If not do you know of any code that could work around this?


  5. Can this method be used to exclude posts, by post tags?

    I have a need to not display ads on certain posts. I don’t want to do it by category though. Really need to do it by tags, instead. For instance… any post tagged with ‘AdFree’ wouldn’t display ads.

    I’m not that good with the coding side of things, but could probably fumble my way through it if I had a little guidance.

    Someone else suggested using custom fields in the posts I want to hide ads, but didn’t elaborate, so I’m no further forward.

    Any help would be appreciated. 🙂

    • It is possible, but not using the methods described above. This is for targeting different line items against different pages (although you could change the targeting criteria to post tags).

      On one WordPress site I did setup an extra field on the post called “Suppress Ads”. Then in the template (single.php), I checked against this field, and only made the ad call if it was not set. This site was using standard adsense rather than DFP.

      I can’t give instructions here, as it would be the subject of a whole blog post.

  6. I repost my head and body sections because there are some things that are missing.

    HEAD Section:

    var googletag = googletag || {};
    googletag.cmd = googletag.cmd || [];
    (function() {
    var gads = document.createElement(‘script’);
    gads.async = true;
    gads.type = ‘text/javascript’;
    var useSSL = ‘https:’ == document.location.protocol;
    gads.src = (useSSL ? ‘https:’ : ‘http:’) +
    var node = document.getElementsByTagName(‘script’)[0];
    node.parentNode.insertBefore(gads, node);

    googletag.cmd.push(function() {

    googletag.defineSlot(‘/1082025/Monopoli_Skin_Playmobil’, [1898, 1249], ‘div-gpt-ad-1466760395979-0’).addService(googletag.pubads());


    BODY Section:

    googletag.cmd.push(function() { googletag.display(‘div-gpt-ad-1466760395979-0’); });

    Thanks a lot!

    • You haven’t actually put a URL into the setTargeting method.


      You left it blank? You should be setting it to the URL of the page.

  7. Hi james,

    real good tutorial, but as long as i am very new to dfp i just can’t make it work. I want to target a specific category in my site and its subcategories and its contents. Let me tell you what i have done:
    1) I created a key value :url /my-page-url
    2) i add it in the line item like this: key-values select url select is select /my-page-url and add it under the placement.
    3) This is my code in the head and body section in the header.php:
    HEAD Section:

    var googletag = googletag || {};
    googletag.cmd = googletag.cmd || [];
    (function() {
    var gads = document.createElement(‘script’);
    gads.async = true;
    gads.type = ‘text/javascript’;
    var useSSL = ‘https:’ == document.location.protocol;
    gads.src = (useSSL ? ‘https:’ : ‘http:’) +
    var node = document.getElementsByTagName(‘script’)[0];
    node.parentNode.insertBefore(gads, node);

    googletag.cmd.push(function() {

    googletag.defineSlot(‘/1082025/Monopoli_Skin_Playmobil’, [1898, 1249], ‘div-gpt-ad-1466760395979-0’).addService(googletag.pubads());


    BODY Section:

    googletag.cmd.push(function() { googletag.display(‘div-gpt-ad-1466760395979-0’); });

    But my skin isn’t displaying…where is the wrong? What do i have to do?

    Please help me because it is really important right now in my job!
    Thanks a lot,


  8. Hi James,

    This post is a life saver!

    Quick question – DFP can support a regex pattern as a ‘value’ to the ‘url’ key, right?

    • From memory I think they only allow a wildcard match using asterisk *, and a tilde ~ to search for a word within the string. It’ll be in their documentation somewhere.

  9. Hi,

    How do you go about this?

    1. I dont know shit about coding but I will like to Implement this targeting for my website. Can you please tell me how to get the code?

    2. Is possible to target sub categories on my website?


  10. Hi, May i have your assistance please in this concern in DFP?

    When i try to use the key value while targeting setting, DFP shows the inventory space as unavailable. But when i target the ad unit without key values, DFP inventory spaces are available. May i know how to fix this issue?

    • I’ve found the DFP inventory estimator to be quite unreliable.

  11. how to make Matched content code in dfp ?

    • You could probably serve the code (copied from adsense) as a line item on DFP? I haven’t tried it but it might work.

  12. if I want to exclude only the home page how can I do that I try “/” or “home” but it doesn’t work

    • I would love to know how to do this as well – tried / but didn’t work.

  13. For the value (the URL of the page) seen as “/my-page-url” in your example:


    Does this url contain the entire website link or just the ending page?

    For example if I want to run on the photo page on, do I need to set up the display ad to run on and then create the value in the extra javascript code to be (“url”,”/photo-page”)?

    In a nutshell, does the 40 character max include the domain and full url or just the specific page you’re targeting?

    • Just the page. You don’t need to include the host or domain name.

  14. Hello,

    Great article, I think it will help me with a client’s WordPress site that needs about the same thing as you describe here. I have a small question though.

    I have multiple ad slots that load on the post page and I want to only target a specific slot (300x250_TOP2) and not all. Right now my code is like that:

    googletag.cmd.push(function() {
    googletag.defineSlot(‘/15840343/300x250_Top1’, [300, 250], ‘div-gpt-ad-1435738869386-6’).addService(googletag.pubads()).setCollapseEmptyDiv(true);
    googletag.defineSlot(‘/15840343/300x250_TOP2’, [300, 250], ‘div-gpt-ad-1435738869386-14’).addService(googletag.pubads()).setCollapseEmptyDiv(true);
    googletag.defineSlot(‘/15840343/300x250_TOP3’, [300, 250], ‘div-gpt-ad-1445424396147-19’).addService(googletag.pubads()).setCollapseEmptyDiv(true);
    googletag.defineSlot(‘/15840343/TEXT_LINK’, [300, 100], ‘div-gpt-ad-1445938982778-19’).addService(googletag.pubads()).setCollapseEmptyDiv(true);

    If I add a targeting criteria, this criteria will apply on all slots right? How can I make it apply to only to one slot (300x250_TOP2)?

    • This is set from within DFP itself from memory. The line item should be targeted only towards a specific slot.

      • Yes, you’re right, it seems it works just fine, for that slot only.

        Thank you for all the help :o)

  15. Hi James.

    Good post. I have been using a similar approach but instead of using the page url substring I have used the post ID (my site is powered by WordPress so getting the post ID is very easy by using $post->ID ). In DFP I have a Free-Form type entry under Key-Values.

    Here is an example (view source code in your browser and look for the DFP tag):

    Of course, the URL approach has some additional benefits, for instance you can target any other page beyond posts, in my case, that was no needed (at least for now).

  16. Hi! Just wanted to check if you received my email regarding freelance work?

    • Did reply, but the email eventually bounced…

  17. Thanks for this tutorial! I was able to use this method to make URL targeting work on Drupal 7. If you don’t mind I’d like to post how that I did it.

    Just as a quick overview for others who may be looking for a solution here’s what I did:

    1) Installed the DFP module for Drupal.
    2) I only have one ad slot that’s set to ROS so for the default ad pattern I used: AD_UNIT_NAME/[dfp_tag:slot] – You’ll need a reasonably good grasp on how to use tokens if your site has more ad units.
    3) The key to getting this going in Drupal is under the Global DFP Settings > Inject Javascript tag is to use the second field (Inject Javascript 2) and use the JS that James describes in this blog and the use Javascript to get the path location:

    googletag.pubads().setTargeting(“url”, window.location.pathname);

    The reason for doing this is that the Inject Javascript field values are stored as Drupal system variables and can’t render php.

    Now you can do your targeting at the line-item in DFP, rather than using the Drupal block system (which is not at all good for this kind of setup). I’m trying to setup sponsorship style ads. I run a non-profit website with 1 ad slot that only appears on certain pages, not ROS. In setting it up this way I basically lose ROS capability for that slot. My solution to get around this would to create another slot for the site and just give the sponsored ad prominence in my layout/design. There may be a better way but I’m new to DFP.

    Thanks again for this great post James. It was very helpful.

  18. Hi James, I’ve been playing with this, this evening and it’s helped me immensely – thank you.

    One small issue I have though, is that on my homepage/root URL the code is (bizarrely) pulling in the URL of the ‘latest published article’ and I can’t for the life of my work out why?

    Is this a weird quirk of WordPress or am I a complete idiot?

    • You’re not a complete idiot. As the home page probably runs the typical WordPress loop you are just getting the value of the latest post ID. You might want to only run your code if not the home page. I think the WP function is is_home().

      • Just a slight idiot then? 🙂

        Thanks for this. Having played a little more last night it does the same on every /category/ page too – so figured this was the case. I’ll see what I can sort out.

        On another note, although the URL is parsing back to DFP, I can’t get the ad to serve to the specific ~VALUE at all.

        So for a url of ‘’ I’m trying to target ALL urls that include ‘value’ but the tilda in custom criteria ain’t cutting it.

        Any ideas? (Maybe I should just hire you on a day rate? ‘p)

  19. Would this work as well James?

    Targeting my smsfs section

    googletag.pubads().setTargeting(‘slug’, ‘/smsfs.html’);

    • Yes, in DFP your targeting key would be “slug” instead of “url” like I have in my example.

  20. Great info, thank you! Does this method allow you to target any occurrence of a particular word within the URL? E.g. if I had:

    And wanted to target all pages that displayed Belts, how would I go about it?

    • According to DFP you can do this:

      Use ~ for ‘includes’ match (~value) or * for ‘begins with’ match (value*)

      So for your target url you could say ~belts and the line item will go to all URLs with belts in it.

  21. Hi James.
    I’m using DFP SB and I don’t understand how to use custom targeting with dynamic pages.
    For example, I have a page /seccion.asp?subcat=12
    If I define key=subcat and value=12 doesn’t work.
    What’s wrong?
    It’s necessary define all combinations of keys for a dynamic page?

    • DFP doesn’t know anything about your CMS’s internal structure. If you wanted to send a certain ad to subcat=12 would have to set that as the URL in the custom criteria.

      DFP is kinda tricky. Every time I get a question on this I have to dive off to DFP as it’s so complex.

  22. I’m using DFP small business, how do I have ads appear by specific keywords that appear in the article/title? I set the free form key ~topic* on the line item but it doesn’t seem to work. Do I have to change something on the actual dfp ad unit code itself as well?

  23. Hi James,

    “Unfortunately DFP restricts criteria value to 40 characters” thank you so much for this information! This is not well documented.

    Cheers Michi

    • I have this working on DFP SB using the method mentioned on the forum (custom targeting and custom criteria). I’m unaware what additional features DFP Premium has as I don’t use that.

      However this tutorial shows how I got the URL targeting to work.

Add a Comment