広告の変更

レスポンシブ検索広告を変更

前述のとおり、変更できるのは特定の広告タイプのみです。次のコードサンプルは、既存のレスポンシブ検索広告を変更する方法を示しています。

Java

private void runExample(GoogleAdsClient googleAdsClient, long customerId, long adId) {
  // Creates an AdOperation to update an ad.
  AdOperation.Builder adOperation = AdOperation.newBuilder();

  // Creates an Ad in the update field of the operation.
  Ad.Builder adBuilder =
      adOperation
          .getUpdateBuilder()
          .setResourceName(ResourceNames.ad(customerId, adId))
          .addFinalUrls("http://www.example.com/")
          .addFinalMobileUrls("http://www.example.com/mobile");

  // Sets the responsive search ad properties to update on the ad.
  adBuilder
      .getResponsiveSearchAdBuilder()
      .addAllHeadlines(
          ImmutableList.of(
              AdTextAsset.newBuilder()
                  .setText("Cruise to Pluto #" + getShortPrintableDateTime())
                  .setPinnedField(ServedAssetFieldType.HEADLINE_1)
                  .build(),
              AdTextAsset.newBuilder().setText("Tickets on sale now").build(),
              AdTextAsset.newBuilder().setText("Buy your ticket now").build()))
      .addAllDescriptions(
          ImmutableList.of(
              AdTextAsset.newBuilder().setText("Best space cruise ever.").build(),
              AdTextAsset.newBuilder()
                  .setText("The most wonderful space experience you will ever have.")
                  .build()));

  // Sets the update mask (the fields which will be modified) to be all the fields we set above.
  adOperation.setUpdateMask(FieldMasks.allSetFieldsOf(adBuilder.build()));

  // Creates a service client to connect to the API.
  try (AdServiceClient adServiceClient =
      googleAdsClient.getLatestVersion().createAdServiceClient()) {
    // Issues the mutate request.
    MutateAdsResponse response =
        adServiceClient.mutateAds(
            String.valueOf(customerId), ImmutableList.of(adOperation.build()));

    // Displays the result.
    for (MutateAdResult result : response.getResultsList()) {
      System.out.printf("Ad with resource name '%s' was updated.%n", result.getResourceName());
    }
  }
}
      

C#

public void Run(GoogleAdsClient client, long customerId, long adId)
{
    // Get the AdService.
    AdServiceClient adService = client.GetService(Services.V16.AdService);

    Ad ad = new Ad()
    {
        ResourceName = ResourceNames.Ad(customerId, adId),
        ResponsiveSearchAd = new ResponsiveSearchAdInfo()
        {
            // Update some properties of the responsive search ad.
            Headlines =
            {
                new AdTextAsset()
                {
                    Text = "Cruise to Pluto #" + ExampleUtilities.GetShortRandomString(),
                    PinnedField = ServedAssetFieldTypeEnum.Types.ServedAssetFieldType.Headline1
                },
                new AdTextAsset() { Text = "Tickets on sale now" },
                new AdTextAsset() { Text = "Buy your ticket now" }
            },
            Descriptions =
            {
                new AdTextAsset() { Text = "Best space cruise ever." },
                new AdTextAsset() { Text = "The most wonderful space experience you will ever have." },
            }
        },
        FinalUrls = { "http://www.example.com/" },
        FinalMobileUrls = { "http://www.example.com/mobile" }
    };

    AdOperation operation = new AdOperation()
    {
        Update = ad,
        UpdateMask = FieldMasks.AllSetFieldsOf(ad)
    };

    try
    {
        // Issue the update request.
        MutateAdsResponse response = adService.MutateAds(customerId.ToString(),
            new[] { operation });

        // Display the results.
        foreach (MutateAdResult updatedAd in response.Results)
        {
            Console.WriteLine($"Ad with resource ID = '{updatedAd.ResourceName}' was " +
                $"updated.");
        }
    }
    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,
    int $adId
) {
    // Creates an ad with the specified resource name and other changes.
    $ad = new Ad([
        'resource_name' => ResourceNames::forAd($customerId, $adId),
        'responsive_search_ad' => new ResponsiveSearchAdInfo([
            // Update some properties of the responsive search ad.
            'headlines' => [
                new AdTextAsset([
                    'text' => 'Cruise to Pluto #' . Helper::getShortPrintableDatetime(),
                    'pinned_field' => ServedAssetFieldType::HEADLINE_1
                ]),
                new AdTextAsset(['text' => 'Tickets on sale now']),
                new AdTextAsset(['text' => 'Buy your ticket now'])
            ],
            'descriptions' => [
                new AdTextAsset(['text' => 'Best space cruise ever.']),
                new AdTextAsset([
                    'text' => 'The most wonderful space experience you will ever have.'])
            ]
        ]),
        'final_urls' => ['http://www.example.com'],
        'final_mobile_urls' => ['http://www.example.com/mobile']
    ]);

    // Constructs an operation that will update the ad, using the FieldMasks to derive the
    // update mask. This mask tells the Google Ads API which attributes of the ad you want to
    // change.
    $adOperation = new AdOperation();
    $adOperation->setUpdate($ad);
    $adOperation->setUpdateMask(FieldMasks::allSetFieldsOf($ad));

    // Issues a mutate request to update the ad.
    $adServiceClient = $googleAdsClient->getAdServiceClient();
    $response =
        $adServiceClient->mutateAds(MutateAdsRequest::build($customerId, [$adOperation]));

    // Prints the resource name of the updated ad.
    /** @var Ad $updatedAd */
    $updatedAd = $response->getResults()[0];
    printf(
        "Updated ad with resource name: '%s'.%s",
        $updatedAd->getResourceName(),
        PHP_EOL
    );
}
      

Python

def main(client, customer_id, ad_id):
    ad_service = client.get_service("AdService")
    ad_operation = client.get_type("AdOperation")

    # Update ad operation.
    ad = ad_operation.update
    ad.resource_name = ad_service.ad_path(customer_id, ad_id)

    # Update some properties of the responsive search ad.
    headline_1 = client.get_type("AdTextAsset")
    headline_1.text = f"Cruise to Pluto #{uuid4().hex[:8]}"
    headline_1.pinned_field = client.enums.ServedAssetFieldTypeEnum.HEADLINE_1

    headline_2 = client.get_type("AdTextAsset")
    headline_2.text = "Tickets on sale now"

    headline_3 = client.get_type("AdTextAsset")
    headline_3.text = "Buy your tickets now"

    ad.responsive_search_ad.headlines.extend(
        [headline_1, headline_2, headline_3]
    )

    description_1 = client.get_type("AdTextAsset")
    description_1.text = "Best space cruise ever."

    description_2 = client.get_type("AdTextAsset")
    description_2.text = (
        "The most wonderful space experience you will ever have."
    )

    ad.final_urls.append("https://www.example.com")
    ad.final_mobile_urls.append("https://www.example.com/mobile")
    client.copy_from(
        ad_operation.update_mask, protobuf_helpers.field_mask(None, ad._pb)
    )

    # Updates the ad.
    ad_response = ad_service.mutate_ads(
        customer_id=customer_id, operations=[ad_operation]
    )
    print(
        f'Ad with resource name "{ad_response.results[0].resource_name}" '
        "was updated."
    )
      

Ruby

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

  ad_resource_name = client.path.ad(customer_id, ad_id)

  # Create the operation for updating the ad.
  ad_operation = client.operation.update_resource.ad(ad_resource_name) do |ad|
    ad.final_urls << 'http://www.example.com'
    ad.final_mobile_urls << 'http://www.example.com/mobile'
    ad.responsive_search_ad = client.resource.responsive_search_ad_info do |rsa|
      rsa.headlines += [
        client.resource.ad_text_asset do |ata|
          ata.text = "Cruise to Pluto #{(Time.new.to_f * 100).to_i}"
          ata.pinned_field = :HEADLINE_1
        end,
        client.resource.ad_text_asset do |ata|
          ata.text = "Tickets on sale now"
        end,
        client.resource.ad_text_asset do |ata|
          ata.text = "Buy your ticket now"
        end,
      ]
      rsa.descriptions += [
        client.resource.ad_text_asset do |ata|
          ata.text = "Best space cruise ever"
        end,
        client.resource.ad_text_asset do |ata|
          ata.text = "The most wonderful space experience you will ever have"
        end,
      ]
    end
  end

  # Update the ad.
  response = client.service.ad.mutate_ads(
    customer_id: customer_id,
    operations: [ad_operation],
  )

  puts "Updated responsive search ad #{response.results.first.resource_name}."
end
      

Perl

sub update_responsive_search_ad {
  my ($api_client, $customer_id, $ad_id) = @_;

  # Create an ad with the proper resource name and any other changes.
  my $ad = Google::Ads::GoogleAds::V16::Resources::Ad->new({
      resourceName => Google::Ads::GoogleAds::V16::Utils::ResourceNames::ad(
        $customer_id, $ad_id
      ),
      responsiveSearchAd =>
        Google::Ads::GoogleAds::V16::Common::ResponsiveSearchAdInfo->new({
          # Update some properties of the responsive search ad.
          headlines => [
            Google::Ads::GoogleAds::V16::Common::AdTextAsset->new({
                text        => "Cruise to Pluto #" . uniqid(),
                pinnedField => HEADLINE_1
              }
            ),
            Google::Ads::GoogleAds::V16::Common::AdTextAsset->new({
                text => "Tickets on sale now"
              }
            ),
            Google::Ads::GoogleAds::V16::Common::AdTextAsset->new({
                text => "Buy your ticket now"
              }
            ),

          ],
          descriptions => [
            Google::Ads::GoogleAds::V16::Common::AdTextAsset->new({
                text => "Best space cruise ever."
              }
            ),
            Google::Ads::GoogleAds::V16::Common::AdTextAsset->new({
                text =>
                  "The most wonderful space experience you will ever have."
              }
            ),
          ]}
        ),
      finalUrls       => ["http://www.example.com/"],
      finalMobileUrls => ["http://www.example.com/mobile"]});

  # Create an ad operation for update, using the FieldMasks utility to derive
  # the update mask.
  my $ad_operation =
    Google::Ads::GoogleAds::V16::Services::AdService::AdOperation->new({
      update     => $ad,
      updateMask => all_set_fields_of($ad)});

  # Issue a mutate request to update the ad.
  my $ads_response = $api_client->AdService()->mutate({
      customerId => $customer_id,
      operations => [$ad_operation]});

  printf "Updated ad with resource name: '%s'.\n",
    $ads_response->{results}[0]{resourceName};

  return 1;
}