When building the Google Shopping campaigns, a split between branded traffic and non-branded traffic is often chosen. The statistics of branded campaigns are often more positive than non-branded campaigns and to optimize bids, it is advisable to make this split into accounts.

By using the prioritization in Shopping campaigns, non-branded search terms enter the campaign with the highest priority. In this campaign, branded search terms are excluded, so that you now have a branded and a non-branded campaign.

Practice

Although in theory a nice structure of the campaign structure, in practice it always appears that this is not watertight. Despite the proper setting of the priorities and exclusions, we will receive non-branded search terms in the branded campaigns. This is annoying for account optimization, because there is now too high a bid for non-branded search terms. The only solution is to exclude all non-branded terms in the brand campaigns. Because this can take a lot of time if you do this manually, we have automated this process with the script below.

How it works

This scripts works for different campaign structures. To use this script, the tree structure in an ad group must be broken down to product level. The script examines for each ad group which product groups are contained therein, collects the brand names of these product groups and then compares them with the search terms in the ad groups. Does none of the brand names appear in the search terms? Then the search term is excluded.

To make sure all brandnames are found, the brandname will be split if existing out of multiple words. Each separate word will be checked in the query. You can also enable the check for acronyms.

Settings

To run this script properly, you don't have to set much:

  • LOG: Specify whether the script should report the intermediate steps, by adjusting the value to 'true'.
  • PRODUCT_FEED_URL: Enter the URL of the XML product feed as it appears in the Google Merchant Center
  • LABEL_ADGROUPS: To keep track of script progress, all ad groups are tagged when they are checked.
  • FILTER_CAMPAIGN_NAME: Use this filter to select branded campaigns only based on the campaign name.
  • USE_ACRONYMS: To use acronyms as brandname, set to true. Otherwise set to false
  • BRAND_MAPPING_SHEET_URL: Optionally, use a spreadsheet for brand typo's or different languages
  • BRAND_MAPPING_SHEET_NAME: When using the spreadsheet, set the sheetname
Script
// Copyright 2019. Increase BV. All Rights Reserved.
//
// Created By: Tibbe van Asten
// for Increase B.V.
// 
// Created: 21-03-2019
// Last update: 12-06-2019
//
// ABOUT THE SCRIPT
// With this script you can exclude non-branded queries 
// from branded shopping campaigns. The brand is taken from the productfeed.
// By doing this every day, the accountstructure will remain clean.
//
////////////////////////////////////////////////////////////////////

var config = {
  
  LOG : true,  
  
  // Get the productfeed URL (XML feed) you use in Google Merchant Center
  PRODUCT_FEED_URL : "PRODUCT_FEED_URL.xml",
  
  // Label all checked adgroups.
  LABEL_ADGROUPS : "Non-Brand Excluded",
  
  // Select only your branded campaigns by campaignname
  FILTER_CAMPAIGN_NAME : "[B]",
  
  // If you don't want to use acronyms as brandname, set to false
  USE_ACRONYMS : true,
  
  // Optionally, use a spreadsheet for brand typo's or different languages
  // Copy the following sheet: https://docs.google.com/spreadsheets/d/1fAxCYsksEljl71LljDzk4jkfBtSTg2ur1zyGnvXOU1E/copy
  // Leave empty when you don't want to use this
  BRAND_MAPPING_SHEET_URL : "https://docs.google.com/spreadsheets/d/1fAxCYsksEljl71LljDzk4jkfBtSTg2ur1zyGnvXOU1E/edit",
  BRAND_MAPPING_SHEET_NAME : "Mapping"
  
}

////////////////////////////////////////////////////////////////////

function main() {
  
  checkLabel();
  var feed = connectFeed();  
  var values = connectSheet();
  var adGroupIterator = selectAdgroups();  
  
  // When all adgroups are checked, all labels will be removed to start again
  if(!adGroupIterator.hasNext()) {
      var adGroupIterator = AdsApp
        .shoppingAdGroups()
        .withCondition("LabelNames CONTAINS_ANY ['"+config.LABEL_ADGROUPS+"']")
        .get();
    
      while(adGroupIterator.hasNext()) {
    	var adGroup = adGroupIterator.next(); 
        adGroup.removeLabel(config.LABEL_ADGROUPS);
      }    
  }
  
  while(adGroupIterator.hasNext()){
    var adGroup = adGroupIterator.next(); 
    	
    	if(config.LOG === true){
          Logger.log("Campaign: " + adGroup.getCampaign().getName() + ", Adgroup: " + adGroup.getName());
          Logger.log("---");
        }
    
    var brands = [];
    var brands = selectBrands(adGroup, feed, brands, values);
    
    if(brands.length > 0){
    
      // Select queries within this adgroup
      var report = AdsApp.report(
        "SELECT Query " +
        "FROM SEARCH_QUERY_PERFORMANCE_REPORT " +
        "WHERE AdGroupId = '" + adGroup.getId() + "' " +
        "AND QueryTargetingStatus = NONE"
      );

      var rows = report.rows();
      while (rows.hasNext()) {
        var row = rows.next();

        var query = trimQuery(row);
        
        // This variable will define if a query is excluded or not. If false, the query will
        // be excluded. If set to true, we will keep the query.
        var match = false;

        for(var i = 0;i < brands.length;i++){

          var brandSplitLenght = brands[i].replace(/[0-9]/g, " ").replace("'", " ").replace("-", " ").replace("&", "").replace("  ", " ").split(" ").length;
          var brandSplit = brands[i].replace(/[0-9]/g, " ").replace("'", " ").replace("-", " ").replace("&", "").replace("  ", " ").split(" ");

          // It's possible that parts of a brandname are present in a query.
          // In that case, we will treat the query as branded
          if(brandSplitLenght > 1) {
            for (var x = 0; x < brandSplit.length; x++) {  

              if((query.indexOf(brandSplit[x]) > -1 || query.indexOf(brandSplit[x].replace("é", "e")) > -1) && brandSplit[x].match(/[a-z]/g).length > 1){
                var match = true;
                break;
              }      
            }
          }

          // After looking at parts of the brandname, we want to know if the brandname
          // is present or the brandname without numbers or spaces is present in the query.
          if(match === false && (query.indexOf(brands[i]) > 1  || query.indexOf(brandSplit) > -1)) {
            var match = true;
            break;
          }  
          
          // The last thing we'll check, is acronyms. Like th for Tommy Hilfiger or hb for Hugo Boss
          // These therms will also not be excluded
          if(match === false && brandSplitLenght > 1 && config.USE_ACRONYMS === true){
            var acronym = brands[i].match(/\b(\w)/g).join('').toLowerCase();
            
            if(query.indexOf(acronym) > -1){
              var match = true;              
              break;
            }       
          }

        } // brandsIterator
        
        // If no match is found in the query, we will exclude the query from the adgroup
        if(match === false){
          adGroup.createNegativeKeyword(query);

          Logger.log("EXCLUDED: " + query + " in " + adGroup.getName());         
        } else{
          if(config.LOG === true){
            Logger.log(query);
          } 
        }

      } // rowIterator
      
      	if(config.LOG === true){
          Logger.log(" ");
        }
      
    } // if brands exist
    
    adGroup.applyLabel(config.LABEL_ADGROUPS);
    
  } // adGroupIterator
  
  Logger.log(" ");
  Logger.log("Thanks for using this custom script by Tibbe van Asten. Winning!");
  
} // function main()

////////////////////////////////////////////////////////////////////

function connectFeed(product) {
  
  if(config.PRODUCT_FEED_URL == "PRODUCT_FEED_URL.xml") {
  	throw error("Change the feed URL in the config"); 
  }
 
  var xml = UrlFetchApp.fetch(config.PRODUCT_FEED_URL).getContentText();
  var document = XmlService.parse(xml);
  var atom = XmlService.getNamespace('http://www.w3.org/2005/Atom');
  var entries = document.getRootElement().getChild('channel').getChildren('item');
  
  return {entries: entries};
  
} // connectFeed()

////////////////////////////////////////////////////////////////////

function connectSheet(){

  if(config.BRAND_MAPPING_SHEET_URL != "" && config.BRAND_MAPPING_SHEET_NAME != ""){
    
    // Connect to the spreadsheet
    var ss = SpreadsheetApp.openByUrl(config.BRAND_MAPPING_SHEET_URL);
    var sheet = ss.getSheetByName(config.BRAND_MAPPING_SHEET_NAME);
    var range = sheet.getDataRange();
    var values = range.getValues();
  
  }
  
  return values;
    
} // connectSheet()

////////////////////////////////////////////////////////////////////

function selectAdgroups(){
  
  if(config.FILTER_CAMPAIGN_NAME == ""){
      
      var adGroupIterator = AdsApp
        .shoppingAdGroups()
        .withCondition("CampaignStatus = ENABLED")
        .withCondition("Clicks > 0")
        .withCondition("LabelNames CONTAINS_NONE ['"+config.LABEL_ADGROUPS+"']")
        .forDateRange("LAST_30_DAYS")
        .get();
      
  } else {
      
      var adGroupIterator = AdsApp
        .shoppingAdGroups()
        .withCondition("CampaignStatus = ENABLED")
        .withCondition("CampaignName CONTAINS_IGNORE_CASE '"+config.FILTER_CAMPAIGN_NAME+"'")
        .withCondition("Clicks > 0")
        .withCondition("LabelNames CONTAINS_NONE ['"+config.LABEL_ADGROUPS+"']")
        .forDateRange("LAST_30_DAYS")
        .get();      
      
  }
  
  return adGroupIterator;
  
} // function selectAdgroups()

////////////////////////////////////////////////////////////////////

function checkLabel(){
  
  if(config.LABEL_ADGROUPS !== "" && !AdsApp.labels().withCondition("Name = '"+config.LABEL_ADGROUPS+"'").get().hasNext()) {
    AdsApp.createLabel(config.LABEL_ADGROUPS);

    	Logger.log("Label " + config.LABEL_ADGROUPS + " created");
    	Logger.log(" ");
  }
  
} // function checkLabel()

////////////////////////////////////////////////////////////////////

function checkBrand(entries, productId) {
  
  var atom = XmlService.getNamespace('http://base.google.com/ns/1.0');
  
  for (var i = 0; i < entries.length; i++) {
    
    if(productId == entries[i].getChild('id', atom).getText()){
      	var brand = entries[i].getChild('brand', atom).getText();
      	break;
    } // if statement

  } // for statement
  
  return brand;
  
} // function checkProduct()

////////////////////////////////////////////////////////////////////

function selectBrands(adGroup, feed, brands, values) {
  
  var products = [];

  var productGroupIterator = adGroup
    .productGroups()
    .withCondition("PartitionType = UNIT")
    .withCondition("ProductGroup DOES_NOT_CONTAIN ' *'")
    .withCondition("ProductGroup DOES_NOT_CONTAIN 'OtherCase'")
    .withCondition("Clicks > 0")
    .forDateRange("LAST_30_DAYS")
    .get();

  while(productGroupIterator.hasNext()){
    var productGroup = productGroupIterator.next();

    products.push(productGroup.getValue());
    var brand = checkBrand(feed.entries, productGroup.getValue()) || "";  

    // Only add new brands
    if(brands.indexOf(brand.toLowerCase()) < 0 && brand != ""){
      brands.push(brand.toLowerCase());
    }
    
    // Check sheet for additional brandname alternatives
    if(brand != "" && config.BRAND_MAPPING_SHEET_URL != "" && config.BRAND_MAPPING_SHEET_NAME != ""){      
      for(var i = 1;i < values.length;i++){
        if(values[i][0] == brand){
          for(var x = 1;x < values[i].length;x++){
            if(brands.indexOf(values[i][x].toLowerCase()) < 0){
              brands.push(values[i][x].toLowerCase());
            }
          } // brandIterator
        }
      } // sheetIterator      
    }

  } // productGroupIterator
  
    if(config.LOG === true){
      Logger.log("ProductGroups: " + products);
      Logger.log("Brands: " + brands);
      Logger.log(" ");
    }
  
  return brands;
  
} // function selectBrands()

////////////////////////////////////////////////////////////////////

function trimQuery(row){
  
  // When the searchquery exceeds the limit of 10 words, we will split
  // the query and put max. 10 words back together as a phrasematch query    	
  var query = "";
  if (row["Query"].split(" ").length < 10) {
    query = "[" + row["Query"] + "]";
  } else {
    for (var i = 0; (i < row["Query"].split(" ").length) && (i < 10); i++){ 
      query += row["Query"].split(" ")[i] + " ";                 
    }
    query = '"' + query.replace(/\s+$/,'') + '"';
  }
  
  return query;
  
} // function trimQuery()

Sharing knowledge

Adsscripts.com is all about sharing knowledge. In the current market, PPC specialists like to keep their knowledge and experience to themselves. We're convinced that sharing knowledge can ensure that everyone gets better at their work. We want to change this by sharing our knowledge about scripts with everyone.

Do you also want to contribute? We are open to new ideas and feedback on everything you find on Adsscripts.com.

Contact us

Nils Rooijmans
Google Ads Scripter
Water Cooler Topics
Nils Rooijmans, Google Ads Scripter
Bas Baudoin
Teamleader PPC
Happy Leads
Bas Baudoin, Teamleider SEA
Tibbe van Asten
PPC Specialist
Founder Adsscripts
Tibbe van Asten, Senior PPC Automation Specialist