I’m pretty happy with a Facebook ads reporting tool that I’ve built.
It lists out all of the campaigns within an ad account, plus all the adsets within each campaign, and all of the ads within each adset.
And it shows the metrics that I care about.
But I’ve been unable to figure out how to retrieve a Post ID from within an ad.
It seems that that field is not mentioned in the Insights edge (is not available within InsightsFields
), so maybe I have to do a “join” on another API call.
My main code for retrieving insights is:
public function getInsights($levelType, $id, $aggLevel, $start, $end) {
if ($levelType) {
if ($id == null) {
abort(500, '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 = 'FacebookAdsObject\' . $levelType;
$level = new $variableClassWithNamespace($id);
$fields = [
InsightsFields::CAMPAIGN_ID,
InsightsFields::CAMPAIGN_NAME,
InsightsFields::ADSET_ID,
InsightsFields::ADSET_NAME,
InsightsFields::AD_ID,
InsightsFields::AD_NAME,
InsightsFields::SPEND,
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();
}
So, at a bare minimum, I’d love to answer this simple question: assuming I have all of the required API permissions (which of course I do), given an ad ID, how can I retrieve the ID of the “post” featured within that ad?
And ideally what I’d love to answer is: how can I retrieve that Post ID within just one API query as I’m retrieving all of the insights that I want (shown above)?
Thanks!
2
Answers
The thing is that post ID is a basic ad parameter, not a daily value you’d get from insights. That’s why it cannot be found anywhere on the insights endpoints.
Assuming you know all the ad IDs, you can query them in all at once (there may be some undocumented limits on the amount in single request) like this:
Which is in fact a shortcut for doing these two queries
You can find more about advanced API usage here in FB docs, in section Multiple ID Read Requests
In case you want to link Facebook Ad Id to Facebook Video Id, you can use a similar query.
Result: