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\v201809\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\v201809\cm\CampaignCriterion; use Google\AdsApi\AdWords\v201809\cm\CampaignCriterionOperation; use Google\AdsApi\AdWords\v201809\cm\CampaignCriterionService; use Google\AdsApi\AdWords\v201809\cm\ConstantOperand; use Google\AdsApi\AdWords\v201809\cm\ConstantOperandConstantType; use Google\AdsApi\AdWords\v201809\cm\ConstantOperandUnit; use Google\AdsApi\AdWords\v201809\cm\FunctionOperator; use Google\AdsApi\AdWords\v201809\cm\Keyword; use Google\AdsApi\AdWords\v201809\cm\KeywordMatchType; use Google\AdsApi\AdWords\v201809\cm\Language; use Google\AdsApi\AdWords\v201809\cm\Location; use Google\AdsApi\AdWords\v201809\cm\LocationExtensionOperand; use Google\AdsApi\AdWords\v201809\cm\LocationGroups; use Google\AdsApi\AdWords\v201809\cm\MatchingFunction; use Google\AdsApi\AdWords\v201809\cm\NegativeCampaignCriterion; use Google\AdsApi\AdWords\v201809\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 AddCampaignTargetingCriteria { 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(); $distance->setRadius($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 ); } } AddCampaignTargetingCriteria::main();
Add negative criteria to a customer
<?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\v201809\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\v201809\cm\ContentLabel; use Google\AdsApi\AdWords\v201809\cm\ContentLabelType; use Google\AdsApi\AdWords\v201809\cm\CustomerNegativeCriterion; use Google\AdsApi\AdWords\v201809\cm\CustomerNegativeCriterionOperation; use Google\AdsApi\AdWords\v201809\cm\CustomerNegativeCriterionService; use Google\AdsApi\AdWords\v201809\cm\Operator; use Google\AdsApi\AdWords\v201809\cm\Placement; use Google\AdsApi\Common\OAuth2TokenBuilder; /** * This example adds various types of negative criteria to a customer. These * criteria will be applied to all campaigns for the customer. */ class AddCustomerNegativeCriteria { public static function runExample( AdWordsServices $adWordsServices, AdWordsSession $session ) { $customerNegativeCriterionService = $adWordsServices->get( $session, CustomerNegativeCriterionService::class ); $criteria = []; // Exclude tragedy & conflict content. $tragedyContentLabel = new ContentLabel(); $tragedyContentLabel->setContentLabelType(ContentLabelType::TRAGEDY); $criteria[] = $tragedyContentLabel; // Exclude a specific placement. $placement = new Placement(); $placement->setUrl('http://www.example.com'); $criteria[] = $placement; // Additional criteria types are available for this service. See the types // listed under Criterion here: // https://developers.google.com/adwords/api/docs/reference/latest/CustomerNegativeCriterionService.Criterion // Create operations to add each of the criteria above. $operations = []; foreach ($criteria as $criterion) { $negativeCriterion = new CustomerNegativeCriterion(); $negativeCriterion->setCriterion($criterion); $operation = new CustomerNegativeCriterionOperation(); $operation->setOperator(Operator::ADD); $operation->setOperand($negativeCriterion); $operations[] = $operation; } // Add the criteria on the server and print out some information. $result = $customerNegativeCriterionService->mutate($operations); foreach ($result->getValue() as $negativeCriterion) { printf( "Customer negative criterion with criterion ID %d and type '%s' was added.\n", $negativeCriterion->getCriterion()->getId(), $negativeCriterion->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); } } AddCustomerNegativeCriteria::main();
Add demographic critera to an ad group
<?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\v201809\BasicOperations; require __DIR__ . '/../../../../vendor/autoload.php'; use Google\AdsApi\AdWords\AdWordsServices; use Google\AdsApi\AdWords\AdWordsSession; use Google\AdsApi\AdWords\AdWordsSessionBuilder; use Google\AdsApi\AdWords\v201809\cm\AdGroupCriterionOperation; use Google\AdsApi\AdWords\v201809\cm\AdGroupCriterionService; use Google\AdsApi\AdWords\v201809\cm\AgeRange; use Google\AdsApi\AdWords\v201809\cm\BiddableAdGroupCriterion; use Google\AdsApi\AdWords\v201809\cm\Gender; use Google\AdsApi\AdWords\v201809\cm\NegativeAdGroupCriterion; use Google\AdsApi\AdWords\v201809\cm\Operator; use Google\AdsApi\Common\OAuth2TokenBuilder; /** * This example adds demographic target criteria to an ad group. * To get ad groups, run AddAdGroup.php. */ class AddDemographicTargetingCriteria { const AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE'; public static function runExample( AdWordsServices $adWordsServices, AdWordsSession $session, $adGroupId ) { $adGroupCriterionService = $adWordsServices->get($session, AdGroupCriterionService::class); $operations = []; // Create biddable ad group criterion for gender. $genderTarget = new Gender(); // ID for "male" criterion. The IDs can be found here: // https://developers.google.com/adwords/api/docs/appendix/genders $genderTarget->setId(10); $genderBiddableAdGroupCriterion = new BiddableAdGroupCriterion(); $genderBiddableAdGroupCriterion->setAdGroupId($adGroupId); $genderBiddableAdGroupCriterion->setCriterion($genderTarget); // Create an ad group criterion operation and add it to the list. $genderBiddableAdGroupCriterionOperation = new AdGroupCriterionOperation(); $genderBiddableAdGroupCriterionOperation->setOperand( $genderBiddableAdGroupCriterion ); $genderBiddableAdGroupCriterionOperation->setOperator(Operator::ADD); $operations[] = $genderBiddableAdGroupCriterionOperation; // Create negative ad group criterion for age range. $ageRangeNegative = new AgeRange(); // Criterion ID for age 18 to 24. The IDs can be found here: // https://developers.google.com/adwords/api/docs/appendix/ages $ageRangeNegative->setId(503001); $ageRangeNegativeAdGroupCriterion = new NegativeAdGroupCriterion(); $ageRangeNegativeAdGroupCriterion->setAdGroupId($adGroupId); $ageRangeNegativeAdGroupCriterion->setCriterion($ageRangeNegative); // Create an ad group criterion operation and add it to the list. $ageRangeNegativeAdGroupCriterionOperation = new AdGroupCriterionOperation(); $ageRangeNegativeAdGroupCriterionOperation->setOperand( $ageRangeNegativeAdGroupCriterion ); $ageRangeNegativeAdGroupCriterionOperation->setOperator(Operator::ADD); $operations[] = $ageRangeNegativeAdGroupCriterionOperation; // Create the ad group criteria on the server and print out some information // for each created ad group criterion. $result = $adGroupCriterionService->mutate($operations); foreach ($result->getValue() as $adGroupCriterion) { printf( "Ad group criterion with ad group ID %d, criterion ID %d and type '%s' was added.\n", $adGroupCriterion->getAdGroupId(), $adGroupCriterion->getCriterion()->getId(), $adGroupCriterion->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::AD_GROUP_ID) ); } } AddDemographicTargetingCriteria::main();
Get all campaign 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\v201809\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\v201809\cm\CampaignCriterionService; use Google\AdsApi\AdWords\v201809\cm\Paging; use Google\AdsApi\AdWords\v201809\cm\Predicate; use Google\AdsApi\AdWords\v201809\cm\PredicateOperator; use Google\AdsApi\AdWords\v201809\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\v201809\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\v201809\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\v201809\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\v201809\cm\LocationCriterionService; use Google\AdsApi\AdWords\v201809\cm\Predicate; use Google\AdsApi\AdWords\v201809\cm\PredicateOperator; use Google\AdsApi\AdWords\v201809\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 { $parentLocationsString = '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();