Stop Close Variant Keywords Script is not working.

102 views
Skip to first unread message

M Kashif

unread,
Oct 3, 2023, 6:50:33 AM10/3/23
to Google Ads Scripts Forum
Hi there,
Please review the code below:

function main() {
  // Get all campaigns
  var campaignIterator = AdsApp.campaigns().get();

  while (campaignIterator.hasNext()) {
    var campaign = campaignIterator.next();

    // Get all ad groups within the campaign
    var adGroupIterator = campaign.adGroups().get();

    while (adGroupIterator.hasNext()) {
      var adGroup = adGroupIterator.next();

      // Get the exact match keywords in the ad group
      var keywordIterator = adGroup.keywords()
        .withCondition("MatchType = EXACT")
        .get();

      // Loop through the exact match keywords and add close variants as negative keywords
      while (keywordIterator.hasNext()) {
        var keyword = keywordIterator.next();
        var keywordText = keyword.getText();

        // Create a negative keyword for the close variant
        var closeVariant = keywordText.replace(/\s+/g, ' ').trim(); // Clean up spaces
        adGroup.createNegativeKeyword('[' + closeVariant + ']');

        Logger.log('Added negative keyword "' + closeVariant + '" to Campaign: ' + campaign.getName() + ', Ad Group: ' + adGroup.getName());
      }
    }
  }
}

i get a lot of :
Add negative keyword errorAn error occurred. Please try again later.


Please let me know what am i doing wrong..

Sigurd Fabrin

unread,
Oct 3, 2023, 8:36:14 AM10/3/23
to Google Ads Scripts Forum
Your variable closeVariant seems to be your keyword text where you've removed extra whitespaces twice. Essentially, you are trying to add your existing positive keyword as a negative. The approach seems strange / something chatGPT would do

You can get search queries from this api report https://developers.google.com/google-ads/api/fields/v14/search_term_view_query_builder and compare them to your keywords - and then add the ones you don't like as negatives. 
Btw: Consider using negative keyword lists as that will be much faster if you have large accounts


Sigurd

Reply all
Reply to author
Forward
0 new messages