标签

您可以使用标签对广告系列、广告组、广告和关键字进行分类,并使用这些类别通过多种方式简化工作流程。

本指南介绍了执行以下操作所需的步骤:

本指南重点介绍广告系列,但您也可以对广告组、广告和关键字采用相同的方法。请注意,该 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