Sitelink Builder Script

Script that enhances your text ads with auto-generated sitelinks

Sitelink Builder Script illustration

How to tap the potential of successful Shopping queries?

The “Sitelink Builder” script automatically creates sitelinks for ad groups in a pre-selected text ad campaign, using spreadsheet data as a source. You need to create the spreadsheet first, ideally using smec's “Shopping Explorer” script which filters and exports successful Google Shopping search queries and related products. High converting products can then be added as sitelinks, helping users navigate to your top performers. Alternatively you can use this spreadsheet template.

Download script and start optimizing

No commitments & no hidden costs — Just a great script

Access and read our
privacy policy.

Success image

Thank you!

You can get the script code below

Arrow down icon
/**
 * Sitelink Builder Script        . * ・ 。゚☆━੧[ ✪ ᗜ ✪ ]⊃
 *
 * Overview: This script creates sitelinks for the specified campaign using a
 * spreadsheet as the source feed for the sitelinks creation. You need to create
 * the spreadsheet first, ideally using smec's Shopping Explorer Script:
 * https://smarter-ecommerce.com/en/adwords-scripts/shopping-explorer/
 *
 * Author: smec [smarter-ecommerce.com]
 *
 * Version: 1.0
 * Changelog:
 * - version 1.0
 *  - Released initial version.
 * Updated: 12-04-2018
 *
 * Twitter: @smec
 * Email: [email protected]
 * (c) Smarter Ecommerce GmbH. All rights reserved.
 * License: MIT
 */

/* ============================ Configuration =============================== */

// Campaign ID of the campaign where sitelinks should be created.
var CAMPAIGN_ID = "YOUR_CAMPAIGN_ID";

// Source data in the form of Google spreadsheet, coming from exploration script.
var SPREADSHEET_ID = "YOUR_SPREADSHEET_ID";

/* ============================== Preferences =============================== */

// Sets the number of sitelinks per ad group.
var MAX_SITELINKS = 4;

// Sets the first description line of the new sitelink description to the specified value.
var DESCRIPTION_LINE_1 = "Description1";

// Sets the second description line of the new sitelink description to the specified value.
var DESCRIPTION_LINE_2 = "Description2";

/* ============================== Execution ================================= */

function main() {
  var spreadsheet = SpreadsheetApp.openById(SPREADSHEET_ID);
  var data = spreadsheet.getDataRange().getValues();

  var campaignIterator = AdWordsApp.campaigns().withIds([CAMPAIGN_ID]).get();
  var activeItems = [];

  for (var i = 1; i < data.length; i++) {
    activeItems.push(data[i][10]);
  }

  if (campaignIterator.totalNumEntities() > 1)
    throw new Error("Provided an invalid number of Campaign Ids");

  while (campaignIterator.hasNext()) {
    var campaign = campaignIterator.next();
    var adGroupIterator = campaign.adGroups().get();
    var sitelinkBuilder = AdWordsApp.extensions().newSitelinkBuilder();

    while (adGroupIterator.hasNext()){
      var adGroup = adGroupIterator.next();
      var existingSitelinks = [];
      var adGroupSitelinkIterator = adGroup.extensions().sitelinks().get();

      // Check if item exists - if not, remove the sitelink from ad group
      while (adGroupSitelinkIterator.hasNext()) {
        var current = adGroupSitelinkIterator.next();

        if (!arrayContains(current.urls().getFinalUrl(), activeItems)) {
          adGroup.removeSitelink(current);
        } else {
          // Keep the sitelinks already active in account (url is used as identifier)
          existingSitelinks.push(current.urls.getFinalUrl);
        }
      }

      Logger.log("----- Creating sitelinks for ad group: " + adGroup.getName() + "-----");

      var sitelinkCount = adGroup.extensions().sitelinks().get().totalNumEntities();

      while (sitelinkCount < MAX_SITELINKS) {
        var adIterator = adGroup.ads().get();
        var randomItem = data[Math.floor(Math.random() * data.length)];
        var sameItem = false;

        if (randomItem[8] != "item not available in MC") {
          while (adIterator.hasNext()){
            var ad = adIterator.next();
            if (ad.urls().getFinalUrl() === randomItem[10]) sameItem = true;
          }
        }

        var finalUrl = randomItem[10];
        var linkText = capitalizeString(randomItem[3]);

        if (!sameItem && linkText.length < 26 && !arrayContains(finalUrl, existingSitelinks)){
          existingSitelinks.push(finalUrl);

          var sitelinkOperation = sitelinkBuilder
              .withLinkText(linkText)
              .withDescription1(DESCRIPTION_LINE_1)
              .withDescription2(DESCRIPTION_LINE_2)
              .withFinalUrl(finalUrl)
              .build();

          if (sitelinkOperation.isSuccessful()) {
            adGroup.addSitelink(sitelinkOperation.getResult());
            sitelinkCount++;
          }
        }
      }
    }
  }
}

function capitalizeString(string) {
  return string.replace(/\b\w/g, function(l){ return l.toUpperCase(); });
}

function arrayContains(needle, arrhaystack) {
  return (arrhaystack.indexOf(needle) > -1);
}

The code was successfully copied to your Clipboard.

Popular Google Ads Scripts

Martin Röttgerding

“Automation can take your PPC efforts to the next level – if you’re doing it right.”

Martin Röttgerding, Head of SEA – Bloofusion Germany

Book a personalized demo

Find out what the AdEngine can do for your business

smec UK hub
smec for UK retailers