標籤

標籤可用來分類廣告活動、廣告群組、廣告和關鍵字,並利用這些類別以各種方式簡化工作流程。

本指南涵蓋以下必要步驟:

本指南著重於廣告活動,但廣告群組、廣告和關鍵字也可以採用相同方法。請注意,API 也提供 CustomerLabelService,可讓管理員帳戶指派標籤給子帳戶。

用途

使用標籤的常見情境包括:

  • 您的帳戶中有隻在一年的特定期間啟用的廣告活動,而您想在報表中輕鬆納入或排除這些廣告活動。
  • 您在廣告群組中加入一組新關鍵字,並想比較這些關鍵字與廣告群組中其他關鍵字的統計資料。
  • Google Ads 帳戶的使用者分別管理一部分的廣告活動,而您想要找出每位使用者的廣告活動組合。
  • 您的應用程式需要標示特定物件的狀態。

建立標籤

使用 TextLabel 物件建立標籤:

  1. 建立 TextLabel 執行個體。
  2. 設定這個 TextLabel 的背景顏色。
  3. 填寫說明欄位來輸入這個 TextLabel 的文字。
  4. TextLabel 納入 LabelOperation,並傳送至 LabelService.MutateLabels

請記下新標籤的 ID,以供後續查詢使用。ID 會嵌入在 MutateLabelsResponse 傳回的 MutateLabelResults 中的 resource_name 欄位中。

您也可以使用 LabelService.GetLabel 要求或 GoogleAdsService SearchSearchStream 要求來擷取 ID。

指派標籤

您可以為廣告活動、客戶、廣告群組、條件或廣告指派標籤。 在適當的服務中使用 Mutate 作業即可指派標籤。

舉例來說,如要將標籤指派給廣告活動,請將一或多個 CampaignLabelOperation 傳遞至 CampaignLabelService.MutateCampaignLabels。每個 CampaignLabelOperation 都包含一個 CampaignLabel 執行個體,其中包含以下欄位:

  • label:標籤 ID
  • campaign:廣告活動的 ID

為每個標籤廣告活動組合建立 CampaignLabel 例項。請使用 create 作業將其納入 CampaignLabelOperation 中,並傳送至 CampaignService.MutateCampaignLabels

新增廣告活動標籤

以下程式碼範例顯示如何將廣告活動標籤新增至廣告活動清單:

Java

private void runExample(
    GoogleAdsClient googleAdsClient, long customerId, List<Long> campaignIds, Long labelId) {
  // Gets the resource name of the label to be added across all given campaigns.
  String labelResourceName = ResourceNames.label(customerId, labelId);

  List<CampaignLabelOperation> operations = new ArrayList<>(campaignIds.size());
  // Creates a campaign label operation for each campaign.
  for (Long campaignId : campaignIds) {
    // Gets the resource name of the given campaign.
    String campaignResourceName = ResourceNames.campaign(customerId, campaignId);
    // Creates the campaign label.
    CampaignLabel campaignLabel =
        CampaignLabel.newBuilder()
            .setCampaign(campaignResourceName)
            .setLabel(labelResourceName)
            .build();

    operations.add(CampaignLabelOperation.newBuilder().setCreate(campaignLabel).build());
  }

  try (CampaignLabelServiceClient campaignLabelServiceClient =
      googleAdsClient.getLatestVersion().createCampaignLabelServiceClient()) {
    MutateCampaignLabelsResponse response =
        campaignLabelServiceClient.mutateCampaignLabels(Long.toString(customerId), operations);
    System.out.printf("Added %d campaign labels:%n", response.getResultsCount());
    for (MutateCampaignLabelResult result : response.getResultsList()) {
      System.out.println(result.getResourceName());
    }
  }
}
      

C#

public void Run(GoogleAdsClient client, long customerId, long[] campaignIds, long labelId)
{
    // Get the CampaignLabelServiceClient.
    CampaignLabelServiceClient campaignLabelService =
        client.GetService(Services.V16.CampaignLabelService);

    // Gets the resource name of the label to be added across all given campaigns.
    string labelResourceName = ResourceNames.Label(customerId, labelId);

    List<CampaignLabelOperation> operations = new List<CampaignLabelOperation>();
    // Creates a campaign label operation for each campaign.
    foreach (long campaignId in campaignIds)
    {
        // Gets the resource name of the given campaign.
        string campaignResourceName = ResourceNames.Campaign(customerId, campaignId);
        // Creates the campaign label.
        CampaignLabel campaignLabel = new CampaignLabel()
        {
            Campaign = campaignResourceName,
            Label = labelResourceName
        };

        operations.Add(new CampaignLabelOperation()
        {
            Create = campaignLabel
        });
    }

    // Send the operation in a mutate request.
    try
    {
        MutateCampaignLabelsResponse response =
            campaignLabelService.MutateCampaignLabels(customerId.ToString(), operations);
        Console.WriteLine($"Added {response.Results} campaign labels:");

        foreach (MutateCampaignLabelResult result in response.Results)
        {
            Console.WriteLine(result.ResourceName);
        }
    }
    catch (GoogleAdsException e)
    {
        Console.WriteLine("Failure:");
        Console.WriteLine($"Message: {e.Message}");
        Console.WriteLine($"Failure: {e.Failure}");
        Console.WriteLine($"Request ID: {e.RequestId}");
        throw;
    }
}
      

PHP

public static function runExample(
    GoogleAdsClient $googleAdsClient,
    int $customerId,
    array $campaignIds,
    int $labelId
) {
    // Gets the resource name of the label to be added across all given campaigns.
    $labelResourceName = ResourceNames::forLabel($customerId, $labelId);

    // Creates a campaign label operation for each campaign.
    $operations = [];
    foreach ($campaignIds as $campaignId) {
        // Creates the campaign label.
        $campaignLabel = new CampaignLabel([
            'campaign' => ResourceNames::forCampaign($customerId, $campaignId),
            'label' => $labelResourceName
        ]);
        $campaignLabelOperation = new CampaignLabelOperation();
        $campaignLabelOperation->setCreate($campaignLabel);
        $operations[] = $campaignLabelOperation;
    }

    // Issues a mutate request to add the labels to the campaigns.
    $campaignLabelServiceClient = $googleAdsClient->getCampaignLabelServiceClient();
    $response = $campaignLabelServiceClient->mutateCampaignLabels(
        MutateCampaignLabelsRequest::build($customerId, $operations)
    );

    printf("Added %d campaign labels:%s", $response->getResults()->count(), PHP_EOL);

    foreach ($response->getResults() as $addedCampaignLabel) {
        /** @var CampaignLabel $addedCampaignLabel */
        printf(
            "New campaign label added with resource name: '%s'.%s",
            $addedCampaignLabel->getResourceName(),
            PHP_EOL
        );
    }
}
      

Python

def main(client, customer_id, label_id, campaign_ids):
    """This code example adds a campaign label to a list of campaigns.

    Args:
        client: An initialized GoogleAdsClient instance.
        customer_id: A client customer ID str.
        label_id: The ID of the label to attach to campaigns.
        campaign_ids: A list of campaign IDs to which the label will be added.
    """

    # Get an instance of CampaignLabelService client.
    campaign_label_service = client.get_service("CampaignLabelService")
    campaign_service = client.get_service("CampaignService")
    label_service = client.get_service("LabelService")

    # Build the resource name of the label to be added across the campaigns.
    label_resource_name = label_service.label_path(customer_id, label_id)

    operations = []

    for campaign_id in campaign_ids:
        campaign_resource_name = campaign_service.campaign_path(
            customer_id, campaign_id
        )
        campaign_label_operation = client.get_type("CampaignLabelOperation")

        campaign_label = campaign_label_operation.create
        campaign_label.campaign = campaign_resource_name
        campaign_label.label = label_resource_name
        operations.append(campaign_label_operation)

    response = campaign_label_service.mutate_campaign_labels(
        customer_id=customer_id, operations=operations
    )
    print(f"Added {len(response.results)} campaign labels:")
    for result in response.results:
        print(result.resource_name)
      

Ruby

def add_campaign_label(customer_id, label_id, campaign_ids)
  # GoogleAdsClient will read a config file from
  # ENV['HOME']/google_ads_config.rb when called without parameters
  client = Google::Ads::GoogleAds::GoogleAdsClient.new

  label_resource_name = client.path.label(customer_id, label_id)

  labels = campaign_ids.map { |campaign_id|
    client.resource.campaign_label do |label|
      campaign_resource_name = client.path.campaign(customer_id, campaign_id)
      label.campaign = campaign_resource_name
      label.label = label_resource_name
    end
  }

  ops = labels.map { |label|
    client.operation.create_resource.campaign_label(label)
  }

  response = client.service.campaign_label.mutate_campaign_labels(
    customer_id: customer_id,
    operations: ops,
  )
  response.results.each do |result|
    puts("Created campaign label with id: #{result.resource_name}")
  end
end
      

Perl

sub add_campaign_labels {
  my ($api_client, $customer_id, $campaign_ids, $label_id) = @_;

  my $label_resource_name =
    Google::Ads::GoogleAds::V16::Utils::ResourceNames::label($customer_id,
    $label_id);

  my $campaign_label_operations = [];

  # Create a campaign label operation for each campaign.
  foreach my $campaign_id (@$campaign_ids) {
    # Create a campaign label.
    my $campaign_label =
      Google::Ads::GoogleAds::V16::Resources::CampaignLabel->new({
        campaign => Google::Ads::GoogleAds::V16::Utils::ResourceNames::campaign(
          $customer_id, $campaign_id
        ),
        label => $label_resource_name
      });

    # Create a campaign label operation.
    my $campaign_label_operation =
      Google::Ads::GoogleAds::V16::Services::CampaignLabelService::CampaignLabelOperation
      ->new({
        create => $campaign_label
      });

    push @$campaign_label_operations, $campaign_label_operation;
  }

  # Add the campaign labels to the campaigns.
  my $campaign_labels_response = $api_client->CampaignLabelService()->mutate({
    customerId => $customer_id,
    operations => $campaign_label_operations
  });

  my $campaign_label_results = $campaign_labels_response->{results};
  printf "Added %d campaign labels:\n", scalar @$campaign_label_results;

  foreach my $campaign_label_result (@$campaign_label_results) {
    printf "Created campaign label '%s'.\n",
      $campaign_label_result->{resourceName};
  }

  return 1;
}
      

使用標籤擷取物件

為廣告活動指派標籤後,您可以使用標籤欄位,依 ID 擷取物件。

將適當的 GAQL 查詢傳遞至 GoogleAdsService SearchSearchStream 要求。舉例來說,以下查詢會傳回與三個標籤 ID 其中之一相關聯的每個廣告活動的 ID、名稱和標籤:

SELECT
  campaign.id,
  campaign.name,
  label.id,
  label.name
FROM campaign_label
WHERE label.id IN (123456, 789012, 345678)

請注意,你只能依標籤 ID 篩選,不能依標籤名稱篩選。如要從標籤名稱取得標籤 ID,您可以使用這個查詢:

SELECT
  label.id,
  label.name
FROM label
WHERE label.name = "LABEL_NAME"

擷取已套用至客戶的標籤

取得管理員帳戶下的帳戶階層時,您可以從 CustomerClient 物件要求 applied_labels 欄位,以擷取套用至子帳戶的標籤清單。這個欄位只會擷取發出 API 呼叫的客戶擁有的標籤。

在報表中使用標籤

標籤報表

「Label」(標籤) 報表資源會傳回帳戶中定義的標籤相關詳細資料。詳細資料包括名稱、ID、資源名稱、狀態、背景顏色和說明,以及代表標籤擁有者的「Customer」資源。

含指標的報表

廣告群組」和「廣告活動」報表檢視畫麵包含 labels 欄位。報表服務會以 customers/{customer_id}/labels/{label_id} 格式傳回標籤資源名稱。例如,資源名稱 customers/123456789/labels/012345 是指 ID 為 123456789 帳戶內 ID 為 012345 的標籤。

不含指標的報表

下列每項報表資源皆可用來找出資源和標籤之間的關係:

您可以使用任何數值比較運算子或 BETWEENIS NULLIS NOT NULLINNOT IN 運算子來比較 label.id 欄位,藉此篩選上述報表結果。

舉例來說,您可以取得具有特定標籤 ID 的所有廣告活動,如下所示:

SELECT
  campaign.id,
  campaign.name,
  label.id,
  label.name
FROM campaign_label
WHERE label.id = LABEL_ID
ORDER BY campaign.id