Targeting Samples

The code samples below provide examples of common targeting functions using the AdWords API. Client Library.

Add targeting criteria to a campaign

<?php
/**
 * Copyright 2017 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
namespace Google\AdsApi\Examples\AdWords\v201710\Targeting;

require __DIR__ . '/../../../../vendor/autoload.php';

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201710\cm\CampaignCriterion;
use Google\AdsApi\AdWords\v201710\cm\CampaignCriterionOperation;
use Google\AdsApi\AdWords\v201710\cm\CampaignCriterionService;
use Google\AdsApi\AdWords\v201710\cm\ConstantOperand;
use Google\AdsApi\AdWords\v201710\cm\ConstantOperandConstantType;
use Google\AdsApi\AdWords\v201710\cm\ConstantOperandUnit;
use Google\AdsApi\AdWords\v201710\cm\FunctionOperator;
use Google\AdsApi\AdWords\v201710\cm\Keyword;
use Google\AdsApi\AdWords\v201710\cm\KeywordMatchType;
use Google\AdsApi\AdWords\v201710\cm\Location;
use Google\AdsApi\AdWords\v201710\cm\LocationExtensionOperand;
use Google\AdsApi\AdWords\v201710\cm\LocationGroups;
use Google\AdsApi\AdWords\v201710\cm\Language;
use Google\AdsApi\AdWords\v201710\cm\MatchingFunction;
use Google\AdsApi\AdWords\v201710\cm\NegativeCampaignCriterion;
use Google\AdsApi\AdWords\v201710\cm\Operator;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example adds various types of targeting criteria to a campaign.
 * To get campaigns, run BasicOperations/GetCampaigns.php.
 */
class AddCampaignTargetingCrtieria {

  const CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE';
  // Replace the value below with the ID of a feed that has been configured for
  // location targeting, meaning it has an ENABLED FeedMapping with
  // criterionType of 77. Feeds linked to a GMB account automatically have this
  // FeedMapping. If you don't have such a feed, set this value to null.
  const LOCATION_FEED_ID = 'INSERT_LOCATION_FEED_ID_HERE';

  public static function runExample(AdWordsServices $adWordsServices,
      AdWordsSession $session, $campaignId, $locationFeedId) {
    $campaignCriterionService =
        $adWordsServices->get($session, CampaignCriterionService::class);

    $campaignCriteria = [];

    // Create locations. The IDs can be found in the documentation or retrieved
    // with the LocationCriterionService.
    $california = new Location();
    $california->setId(21137);
    $campaignCriteria[] =
        new CampaignCriterion($campaignId, null, $california);

    $mexico = new Location();
    $mexico->setId(2484);
    $campaignCriteria[] =
        new CampaignCriterion($campaignId, null, $mexico);

    // Create languages. The IDs can be found in the documentation or retrieved
    // with the ConstantDataService.
    $english = new Language();
    $english->setId(1000);
    $campaignCriteria[] =
        new CampaignCriterion($campaignId, null, $english);

    $spanish = new Language();
    $spanish->setId(1003);
    $campaignCriteria[] =
        new CampaignCriterion($campaignId, null, $spanish);

    if ($locationFeedId !== null) {
      // Distance targeting. Area of 10 miles around targets above.
      $radius = new ConstantOperand();
      $radius->setType(ConstantOperandConstantType::DOUBLE);
      $radius->setUnit(ConstantOperandUnit::MILES);
      $radius->setDoubleValue(10.0);
      $distance = new LocationExtensionOperand($radius);
      $locationGroup = new LocationGroups();
      $locationGroup->setFeedId(intval($locationFeedId));
      $locationGroup->setMatchingFunction(
          new MatchingFunction(FunctionOperator::IDENTITY, [$distance]));
      $campaignCriteria[] =
          new CampaignCriterion($campaignId, null, $locationGroup);
    }

    $operations = [];
    foreach ($campaignCriteria as $campaignCriterion) {
      $operation = new CampaignCriterionOperation();
      $operation->setOperator(Operator::ADD);
      $operation->setOperand($campaignCriterion);
      $operations[] = $operation;
    }

    // Add a negative campaign criterion.
    $negativeKeyword = new Keyword();
    $negativeKeyword->setText('jupiter cruise');
    $negativeKeyword->setMatchType(KeywordMatchType::BROAD);
    $negativeCriterion = new NegativeCampaignCriterion();
    $negativeCriterion->setCampaignId($campaignId);
    $negativeCriterion->setCriterion($negativeKeyword);

    $operation = new CampaignCriterionOperation();
    $operation->setOperator(Operator::ADD);
    $operation->setOperand($negativeCriterion);
    $operations[] = $operation;

    $result = $campaignCriterionService->mutate($operations);

    // Print out some information about added campaign criteria.
    foreach ($result->getValue() as $campaignCriterion) {
      printf(
          "Campaign targeting criterion with ID %d and type '%s' was added.\n",
          $campaignCriterion->getCriterion()->getId(),
          $campaignCriterion->getCriterion()->getType());
    }
  }

  public static function main() {
    // Generate a refreshable OAuth2 credential for authentication.
    $oAuth2Credential = (new OAuth2TokenBuilder())
        ->fromFile()
        ->build();

    // Construct an API session configured from a properties file and the OAuth2
    // credentials above.
    $session = (new AdWordsSessionBuilder())
        ->fromFile()
        ->withOAuth2Credential($oAuth2Credential)
        ->build();
    self::runExample(
        new AdWordsServices(), $session, intval(self::CAMPAIGN_ID),
            self::LOCATION_FEED_ID);
  }
}

AddCampaignTargetingCrtieria::main();

Get all campaign targeting criteria

<?php
/**
 * Copyright 2017 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
namespace Google\AdsApi\Examples\AdWords\v201710\Targeting;

require __DIR__ . '/../../../../vendor/autoload.php';

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201710\cm\CampaignCriterionService;
use Google\AdsApi\AdWords\v201710\cm\Predicate;
use Google\AdsApi\AdWords\v201710\cm\PredicateOperator;
use Google\AdsApi\AdWords\v201710\cm\Paging;
use Google\AdsApi\AdWords\v201710\cm\Selector;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example gets all targeting criteria for a campaign. To add targeting
 * criteria, run AddCampaignTargetingCriteria.php.
 */
class GetCampaignTargetingCriteria {

  const CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE';
  const PAGE_LIMIT = 500;

  public static function runExample(AdWordsServices $adWordsServices,
      AdWordsSession $session, $campaignId) {
    $campaignCriterionService =
        $adWordsServices->get($session, CampaignCriterionService::class);

    // Create a selector to select all campaign criteria for the specified
    // campaign.
    $selector = new Selector();
    $selector->setFields(['Id', 'CriteriaType']);
    $selector->setPredicates([
        new Predicate('CampaignId', PredicateOperator::IN, [$campaignId]),
        new Predicate('CriteriaType', PredicateOperator::IN,
            ['LANGUAGE', 'LOCATION', 'AGE_RANGE', 'CARRIER',
            'OPERATING_SYSTEM_VERSION', 'GENDER', 'PROXIMITY', 'PLATFORM'])
    ]);
    $selector->setPaging(new Paging(0, self::PAGE_LIMIT));

    $totalNumEntries = 0;
    do {
      // Retrieve campaign criteria one page at a time, continuing to request
      // pages until all campaign criteria have been retrieved.
      $page = $campaignCriterionService->get($selector);

      // Print out some information for each campaign criterion.
      if ($page->getEntries() !== null) {
        $totalNumEntries = $page->getTotalNumEntries();
        foreach ($page->getEntries() as $campaignCriterion) {
          printf(
              "Campaign targeting criterion with ID %d and type '%s' was "
                  . "found.\n",
              $campaignCriterion->getCriterion()->getId(),
              $campaignCriterion->getCriterion()->getType()
          );
        }
      }

      $selector->getPaging()->setStartIndex(
          $selector->getPaging()->getStartIndex() + self::PAGE_LIMIT);
    } while ($selector->getPaging()->getStartIndex() < $totalNumEntries);

    printf("Number of results found: %d\n", $totalNumEntries);
  }

  public static function main() {
    // Generate a refreshable OAuth2 credential for authentication.
    $oAuth2Credential = (new OAuth2TokenBuilder())
        ->fromFile()
        ->build();

    // Construct an API session configured from a properties file and the OAuth2
    // credentials above.
    $session = (new AdWordsSessionBuilder())
        ->fromFile()
        ->withOAuth2Credential($oAuth2Credential)
        ->build();
    self::runExample(
        new AdWordsServices(), $session, intval(self::CAMPAIGN_ID));
  }
}

GetCampaignTargetingCriteria::main();

Get all targetable languages and carriers

<?php
/**
 * Copyright 2017 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
namespace Google\AdsApi\Examples\AdWords\v201710\Targeting;

require __DIR__ . '/../../../../vendor/autoload.php';

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201710\cm\ConstantDataService;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example gets all language and carrier criteria available for targeting.
 */
class GetTargetableLanguagesAndCarriers {

  const PAGE_LIMIT = 500;

  public static function runExample(AdWordsServices $adWordsServices,
      AdWordsSession $session) {
    $constantDataService =
        $adWordsServices->get($session, ConstantDataService::class);

    // Retrieve language criteria.
    $languages = $constantDataService->getLanguageCriterion();
    foreach ($languages as $language) {
      printf("Language with name '%s' and ID %d was found.\n",
          $language->getName(), $language->getId());
    }

    print "\n";

    // Retrieve carrier criteria.
    $carriers = $constantDataService->getCarrierCriterion();
    foreach ($carriers as $carrier) {
      printf(
          "Carrier with name '%s', country code '%s', and ID %d was found.\n",
          $carrier->getName(),
          $carrier->getCountryCode(),
          $carrier->getId()
      );
    }
  }

  public static function main() {
    // Generate a refreshable OAuth2 credential for authentication.
    $oAuth2Credential = (new OAuth2TokenBuilder())
        ->fromFile()
        ->build();

    // Construct an API session configured from a properties file and the OAuth2
    // credentials above.
    $session = (new AdWordsSessionBuilder())
        ->fromFile()
        ->withOAuth2Credential($oAuth2Credential)
        ->build();
    self::runExample(new AdWordsServices(), $session);
  }
}

GetTargetableLanguagesAndCarriers::main();

Get location criteria by name

<?php
/**
 * Copyright 2017 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
namespace Google\AdsApi\Examples\AdWords\v201710\Targeting;

require __DIR__ . '/../../../../vendor/autoload.php';

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201710\cm\LocationCriterionService;
use Google\AdsApi\AdWords\v201710\cm\Predicate;
use Google\AdsApi\AdWords\v201710\cm\PredicateOperator;
use Google\AdsApi\AdWords\v201710\cm\Selector;
use Google\AdsApi\Common\OAuth2TokenBuilder;

/**
 * This example looks up location criteria by name.
 */
class LookupLocation {

  public static function runExample(AdWordsServices $adWordsServices,
      AdWordsSession $session) {
    $locationCriterionService =
        $adWordsServices->get($session, LocationCriterionService::class);

    // Location names to look up.
    $locationNames = ['Paris', 'Quebec', 'Spain', 'Deutschland'];
    // Locale to retrieve location names in.
    $locale = 'en';

    // Create a selector to select all locations.
    $selector = new Selector();
    $selector->setFields(['Id', 'LocationName', 'CanonicalName',
        'DisplayType',  'ParentLocations', 'Reach', 'TargetingStatus']);
    // Location names must match exactly, only EQUALS and IN are supported
    // and only one locale can be used in a request.
    $selector->setPredicates([
        new Predicate('LocationName', PredicateOperator::IN, $locationNames),
        new Predicate('Locale', PredicateOperator::EQUALS, [$locale])
    ]);

    // Retrieve location criteria from the server.
    $locationCriteria = $locationCriterionService->get($selector);

    // Print out some information for each location criterion.
    if ($locationCriteria !== null) {
      foreach ($locationCriteria as $locationCriterion) {
        if ($locationCriterion->getLocation()->getParentLocations() !== null) {
          $parentLocations = [];
          foreach ($locationCriterion->getLocation()->getParentLocations()
              as $location) {
            $parentLocations[] = sprintf(
                '%s (%s)',
                $location->getLocationName(),
                $location->getDisplayType()
            );
          }
          $parentLocationsString = implode(', ', $parentLocations);
        } else {
          $parentLocations = 'N/A';
        }
        printf(
            "The search term '%s' returned the location '%s' of type '%s' "
                . "with ID %d, parent locations '%s', and reach %d (%s).\n",
            $locationCriterion->getSearchTerm(),
            $locationCriterion->getLocation()->getLocationName(),
            $locationCriterion->getLocation()->getDisplayType(),
            $locationCriterion->getLocation()->getId(),
            $parentLocationsString,
            $locationCriterion->getReach(),
            $locationCriterion->getLocation()->getTargetingStatus()
        );
      }
    } else {
      print "No location criteria were found.\n";
    }
  }

  public static function main() {
    // Generate a refreshable OAuth2 credential for authentication.
    $oAuth2Credential = (new OAuth2TokenBuilder())
        ->fromFile()
        ->build();

    // Construct an API session configured from a properties file and the OAuth2
    // credentials above.
    $session = (new AdWordsSessionBuilder())
        ->fromFile()
        ->withOAuth2Credential($oAuth2Credential)
        ->build();
    self::runExample(new AdWordsServices(), $session);
  }
}

LookupLocation::main();

Send feedback about...

AdWords API
AdWords API
Need help? Visit our support page.