Etykiety

Etykiety umożliwiają kategoryzowanie kampanii, grup reklam, reklam i słów kluczowych oraz wykorzystywanie tych kategorii do upraszczania przepływu pracy na różne sposoby.

W tym przewodniku znajdziesz informacje o tym, jak:

Ten przewodnik dotyczy kampanii, ale możesz zastosować to samo podejście w przypadku grup reklam, reklam i słów kluczowych. Ten interfejs API udostępnia też CustomerLabelService, który umożliwia kontom menedżera przypisywanie etykiet do kont podrzędnych.

Przypadki użycia

Typowe scenariusze używania etykiet to:

  • Na koncie masz kampanie, które włączasz tylko w określonych porach roku, i chcesz uwzględniać je w raportach lub z nich wykluczać.
  • Do grupy reklam dodano nowy zestaw słów kluczowych i chcesz porównać ich statystyki ze statystykami innych słów kluczowych w tej grupie.
  • Użytkownicy Twojego konta Google Ads zarządzają podzbiorem kampanii i chcesz mieć możliwość identyfikowania zestawu kampanii każdego użytkownika.
  • Aplikacja musi oznaczać stan niektórych obiektów.

Utwórz etykiety

Utwórz etykiety za pomocą obiektu Label z ustawionym polem text_label:

  1. Utwórz instancję TextLabel zawierającą kolor tła i opis.
  2. Utwórz instancję Label i przypisz do jej pola text_label wartość TextLabel.
  3. Owiń Label w LabelOperation (create) i wyślij do LabelService.MutateLabels.

Zapisz identyfikator utworzonej etykiety, aby użyć go w późniejszych zapytaniach. Identyfikator jest umieszczony w polu resource_name w obiekcie MutateLabelResult zwróconym w obiekcie MutateLabelsResponse.

Aby pobrać identyfikatory etykiet i nazwy zasobów, możesz też użyć żądania GoogleAdsService Search lub SearchStream.

Przypisz etykiety

Etykiety możesz przypisywać do kampanii, klientów, grup reklam, kryteriów lub reklam za pomocą operacji Mutate w odpowiedniej usłudze.

Aby na przykład przypisać etykiety do kampanii, przekaż co najmniej 1 obiekt CampaignLabelOperation do CampaignLabelService.MutateCampaignLabels. Każdy element CampaignLabelOperation zawiera instancję CampaignLabel, która wymaga pełnych nazw zasobów w tych polach:

  • label: nazwa zasobu etykiety (np. customers/{customer_id}/labels/{label_id}).
  • campaign: nazwa zasobu kampanii (np.customers/{customer_id}/campaigns/{campaign_id}).

Utwórz CampaignLabel dla każdej pary etykieta–kampania. Owiń go w CampaignLabelOperation za pomocą operacji create i wyślij do CampaignLabelService.MutateCampaignLabels.

Dodawanie etykiet kampanii

Oto przykład kodu pokazujący, jak dodać etykietę kampanii do listy kampanii:

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.V25.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: GoogleAdsClient,
    customer_id: str,
    label_id: str,
    campaign_ids: List[str],
) -> None:
    """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: CampaignLabelServiceClient = client.get_service(
        "CampaignLabelService"
    )
    campaign_service: CampaignServiceClient = client.get_service(
        "CampaignService"
    )
    label_service: LabelServiceClient = client.get_service("LabelService")

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

    operations: List[Any] = []

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

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

    response: MutateCampaignLabelsResponse = (
        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::V25::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::V25::Resources::CampaignLabel->new({
        campaign => Google::Ads::GoogleAds::V25::Utils::ResourceNames::campaign(
          $customer_id, $campaign_id
        ),
        label => $label_resource_name
      });

    # Create a campaign label operation.
    my $campaign_label_operation =
      Google::Ads::GoogleAds::V25::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;
}
      

curl

Przypisywanie etykiet do klientów

Przypisywanie etykiet do klientów to typowe zadanie na kontach menedżera, które służy do kategoryzowania kont klientów. Odbywa się to za pomocą metody CustomerLabelService. Etykiety utworzone na koncie menedżera należą do tego konta i są widoczne tylko wtedy, gdy uwierzytelniono je jako należące do tego konta.

Każdy element CustomerLabelOperation zawiera instancję CustomerLabel. Tworząc relację etykiety klienta, pamiętaj o tych kwestiach:

  • label: to pole jest wymagane i musi zawierać nazwę zasobu etykiety należącej do konta menedżera, np. customers/{MANAGER_ID}/labels/{LABEL_ID}.
  • customer: to pole jest tylko wyjściowe i nie powinno być ustawiane w żądaniu. Klient, któremu przypisywana jest etykieta, jest określany przez parametr customer_id w ścieżce MutateCustomerLabelsRequest.

Pobieranie obiektów za pomocą etykiet

Po przypisaniu etykiet do kampanii możesz użyć pól etykiet, aby pobrać obiekty według identyfikatora.

Przekaż odpowiednie zapytanie GAQL do żądania GoogleAdsService Search lub SearchStream. Na przykład to zapytanie zwraca identyfikator, nazwę i etykiety każdej kampanii powiązanej z jednym z 3 identyfikatorów etykiet:

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

Możesz filtrować tylko według identyfikatora etykiety, a nie jej nazwy. Aby uzyskać identyfikator etykiety na podstawie nazwy etykiety, użyj tego zapytania:

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

Pobieranie etykiet zastosowanych do klienta

Podczas pobierania hierarchii kont podrzędnych konta menedżera możesz uzyskać listę etykiet zastosowanych na koncie klienta podrzędnego, wysyłając żądanie pola applied_labels z obiektu CustomerClient. To pole pobiera tylko etykiety należące do klienta, który wywołuje interfejs API.

Używanie etykiet w raportach

Używaj etykiet, aby zwiększyć przydatność raportów.

Raportowanie etykiet

Zasób raportu Etykieta zwraca szczegółowe informacje o etykietach zdefiniowanych na koncie. Szczegóły obejmują nazwę, identyfikator, nazwę zasobu, stan, kolor tła i opis, a także zasób Klient reprezentujący właściciela etykiety.

Raporty z danymi

Raporty Grupa reklam i Kampania zawierają pole labels. Usługa raportowania zwraca nazwy zasobów etykiet w formacie customers/{customer_id}/labels/{label_id}. Na przykład nazwa zasobu customers/123456789/labels/012345 odnosi się do etykiety o identyfikatorze 012345 na koncie o identyfikatorze 123456789.

Raporty bez danych

Aby znaleźć relacje między zasobami a etykietami, możesz użyć tych zasobów raportu:

Wyniki raportu możesz filtrować, porównując pole label.id za pomocą dowolnego operatora porównania liczbowego lub operatorów BETWEEN, IS NULL, IS NOT NULL, IN lub NOT IN.

W tym przykładzie możesz pobrać wszystkie kampanie z określonym identyfikatorem etykiety:

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