// Copyright 2018. Increase BV. All Rights Reserved.
//
// Created By: Tibbe van Asten
// for Increase B.V.
//
// Last update: 14-06-2018
//
// ABOUT THE SCRIPT
// With this script you can exclude non-branded queries
// from branded shopping campaigns. By doing this
// every day, the accountstructure will remain clean.
// -----------------------------------------------------
// First branded search query. Make sure to use quotes.
var BRANDED_KEYWORD_1 = "X";
// Second branded search query. If you don't use this one, remove line 30.
var BRANDED_KEYWORD_2 = "Y";
// Third branded search query. If you don't use this one, remove line 31.
var BRANDED_KEYWORD_3 = "Z";
// The mark for every branded campaign in the account
var B_SELECTOR = "[B]";
function main() {
// First, we select all search queries in the branded campaigns
// that do not contain any of the branded keywords
var report = AdsApp.report(
'SELECT CampaignName, AdGroupId, AdGroupName, Query ' +
'FROM SEARCH_QUERY_PERFORMANCE_REPORT ' +
'WHERE CampaignStatus = ENABLED AND AdGroupStatus = ENABLED ' +
'AND CampaignName STARTS_WITH_IGNORE_CASE "' + B_SELECTOR + '" ' +
'AND Query DOES_NOT_CONTAIN_IGNORE_CASE ' + BRANDED_KEYWORD_1 +
' AND Query DOES_NOT_CONTAIN_IGNORE_CASE ' + BRANDED_KEYWORD_2 +
' AND Query DOES_NOT_CONTAIN_IGNORE_CASE ' + BRANDED_KEYWORD_3 +
' AND QueryTargetingStatus = NONE '
);
var rows = report.rows();
while (rows.hasNext()) {
var row = rows.next();
var query = "";
// Search queries with over 10 words, can not be excluded in Google Ads.
// So we check the queries and when over 10 words, we will make it a phrase match.
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+$/,'') + '"';
}
var shoppingAdGroupIterator = AdsApp
.shoppingAdGroups()
.withCondition("Id = '"+row["AdGroupId"]+"'")
.withCondition("Clicks > 0")
.forDateRange("LAST_14_DAYS")
.get();
while (shoppingAdGroupIterator.hasNext()) {
var shoppingAdGroup = shoppingAdGroupIterator.next();
Logger.log(row["CampaignName"]);
Logger.log(row["AdGroupName"]);
shoppingAdGroup.createNegativeKeyword(query);
Logger.log(query);
Logger.log(" ");
}
}