Exclude Non-Brand Search Queries From Standard Shopping Campaign

// ----- Settings -----
var SETTINGS = {
    brandKeywords: ['brand', 'brend', 'braand'], // add your brand keywords + misspellings here
    campaignId: '123456789', // add your standard shopping campaign ID here
};

function main() {
    var regexPattern = SETTINGS.brandKeywords.map(function(keyword) {
        return "(?i).*" + keyword.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1") + ".*";
    }).join("|");
    
    var now = new Date();
    var from = new Date(now.getTime() - 24 * 60 * 60 * 1000);
    var timeZone = AdsApp.currentAccount().getTimeZone();
    var formattedFrom = Utilities.formatDate(from, timeZone, 'yyyy-MM-dd');
    var formattedTo = Utilities.formatDate(now, timeZone, 'yyyy-MM-dd');

    var query = [
        "SELECT ad_group.id, search_term_view.search_term",
        "FROM search_term_view",
        "WHERE search_term_view.search_term NOT REGEXP_MATCH '" + regexPattern + "'",
        "AND campaign.id = '" + SETTINGS.campaignId + "'",
        "AND ad_group.status = 'ENABLED'",
        "AND search_term_view.status = 'NONE'",
        "AND metrics.clicks >= 1",
        "AND segments.date BETWEEN '" + formattedFrom + "' AND '" + formattedTo + "'"
    ].join(' ');

    try {
        var report = AdsApp.report(query);
        var rows = report.rows();
        while (rows.hasNext()) {
            var row = rows.next();
            var searchQuery = trimQuery(row["search_term_view.search_term"]);
            addToCampaignNegativeKeywords(SETTINGS.campaignId, searchQuery);
        }
    } catch (e) {
        Logger.log("Error executing query: " + e.message);
    }
}

function trimQuery(query) {
    if (query.length > 80) {
        query = query.substring(0, 80);
    }

    var words = query.split(" ");
    return words.length < 10 ? '[' + query + ']' : '"' + words.slice(0, 10).join(" ") + '"';
}


function addToCampaignNegativeKeywords(campaignId, query) {
    var campaigns = AdsApp.shoppingCampaigns()
        .withIds([campaignId])
        .get();

    if (!campaigns.hasNext()) {
        Logger.log("No campaign found with ID: " + campaignId);
        return;
    }
    var campaign = campaigns.next();
    campaign.createNegativeKeyword(query);
}

Leave a Reply

Your email address will not be published. Required fields are marked *