My code allows me to retrieve all ads that between certain dates, but this includes ads that are no longer active.
I want to show insights only for ACTIVE ads. How can I retrieve Facebook Insights for all active ads within an account?
public function getInsights($levelType, $id, $aggLevel, $start, $end) {
if ($levelType) {
if ($id == null) {
abort(400, 'You must provide the ID for the object you want to retrieve.');
}
} else {
$levelType = \AdAccount::class;
$id = ACT_PREPEND . $this->fbConfig['account_id'];
$aggLevel = AdsInsightsLevelValues::CAMPAIGN;
}
$variableClassWithNamespace = '\FacebookAds\Object\\' . $levelType; //TODO: avoid hard-coding class paths as strings
$level = new $variableClassWithNamespace($id);
$fields = [
InsightsFields::SPEND,
InsightsFields::CAMPAIGN_ID,
InsightsFields::CAMPAIGN_NAME,
InsightsFields::ADSET_ID,
InsightsFields::ADSET_NAME,
InsightsFields::AD_ID,
InsightsFields::AD_NAME,
InsightsFields::UNIQUE_IMPRESSIONS,
InsightsFields::INLINE_LINK_CLICKS,
InsightsFields::INLINE_LINK_CLICK_CTR,
InsightsFields::COST_PER_INLINE_LINK_CLICK,
InsightsFields::ACTIONS,
InsightsFields::COST_PER_ACTION_TYPE,
InsightsFields::CPM,
];
$params = [
AdReportRunFields::LEVEL => $aggLevel,
];
if ($start) {
$params[AdReportRunFields::TIME_RANGE]['since'] = $start;
if (!$end) {
$params[AdReportRunFields::TIME_RANGE]['until'] = (new \DateTime("+2 year"))->format('Y-m-d');
}
}
if ($end) {
$params[AdReportRunFields::TIME_RANGE]['until'] = $end;
if (!$start) {
$params[AdReportRunFields::TIME_RANGE]['since'] = (new \DateTime("-1 year"))->format('Y-m-d');
}
}
if (!$start && !$end) {
$params[AdReportRunFields::DATE_PRESET] = InsightsPresets::LIFETIME;
}
$insights = $level->getInsights($fields, $params);
return $insights->getResponse()->getBody();
}
I'm using the Facebook PHP Ads SDK 2.8 ("facebook/php-ads-sdk": "2.8.*"
in composer.json
). The documentation is here.