YOzaz
YOzaz

Reputation: 23

Deleting completed Facebook AdSets using Marketing API

I am trying to create Facebook Ads cleaner, which deletes completed AdSets in a specified campaign. There's a limit how may non-deleted non-archived AdSets you can have (which is 10000 for bulk accounts), and we are reaching this limit quite quickly.

I am using Marketing API, and Facebook Ads API SDK for PHP: https://github.com/facebook/facebook-php-ads-sdk

While it is clear how AdSets can be retrieved, I can't find a way to filter them by end time. There is a "since" parameter, but it looks like it doesn't filter on AdSet start and end date, and rather filters stats themselves. Therefore AdSet, which is still active, will get into specified range.

My code:

use FacebookAds\Object\Campaign;
use FacebookAds\Object\Fields\AdSetFields;
use Carbon\Carbon;

// Facebook ID of a Ad Campaign
$external_id = '123456789';
$campaign = new Campaign( $external_id );

// Querying required field only
$fields = [
    AdSetFields::END_TIME
];

// Need to query AdSets which have been completed in the past...?
$params = [
];

$adsets = $campaign->getAdSets( $fields, $params );
$adsets->setUseImplicitFetch( true );

while ( $adsets->valid() )
{
    /** @var AdSet $adset */
    $adset = $adsets->current();
    $end_time = Carbon::parse( $adset->{AdSetFields::END_TIME} );

    if ( $end_time->isPast() )
    {
        $adset->delete();
    }

    $adsets->next();
}

The problem: in case there are lots of AdSets in a Campaign, this will literally mean iterating ALL AdSets inside one-by-one and checking it's end date. Usually, we're speaking about thousands of records, and such approach is highly ineffective. As we have lots of ad accounts, "cleaning" script runs forever, even if it doesn't timeout quickly.

Question: is there a way to filter AdSets by end_time? It looks like it is possible by explicitly proving a value, but I can't find a way to filter value using "less than" or "more than" syntax.

Upvotes: 1

Views: 564

Answers (1)

rmx
rmx

Reputation: 71

If adset has completed running, the its effective status will be in 'PAUSED' state. This should return a smaller subset of adsets. You can filter adsets in the PAUSED state and then check for their end time and delete after validation.

Upvotes: 1

Related Questions