Marketing API Version

Custom Audiences from your Website

Overview

This document describes how to use a Custom Audiences Pixel and JavaScript Tag API with a combination of rules to create a custom audience of users who visited or took specific actions on your website.

The term 'custom audiences from your website' refers specifically to custom audiences created with this method. Once a custom audience has been created from a website, it can be referenced in ad targeting the same way standard custom audiences are used and users will get automatically added or removed following the retention policy you have setup.

This doc contains code samples and rules that using old website custom audience pixel code to create website custom audiences. Please upgrade to Facebook pixel to take advantage of the new features going forward. More details on Website Custom Audiences with Facebook Pixel.

Create the Pixel

The following API call can be used to create a Custom Audience Pixel (only needed once per ad account).

use FacebookAds\Object\AdsPixel;
use FacebookAds\Object\Fields\AdsPixelsFields;

$pixel = new AdsPixel(null, 'act_<AD_ACCOUNT_ID>');
$pixel->{AdsPixelsFields::NAME} = 'My WCA Pixel';
$pixel->create();
from facebookads.adobjects.adspixel import AdsPixel

pixel = AdsPixel(parent_id='act_<AD_ACCOUNT_ID>')
pixel[AdsPixel.Field.name] = 'My new Pixel'

pixel.remote_create()
curl \
  -F 'name=My WCA Pixel' \
  -F 'access_token=<ACCESS_TOKEN>' \
  https://graph.facebook.com/v2.8/act_<AD_ACCOUNT_ID>/adspixels

The API will return the pixel ID, and will be in the form of:

{
  "id": "11111"
}
Facebook pixel reference

Read the Pixel Code

The following API call can be used to retrieve the Custom Audience Pixel code

use FacebookAds\Object\AdsPixel;
use FacebookAds\Object\Fields\AdsPixelsFields;

$pixel = new AdsPixel(<PIXEL_ID>, 'act_<AD_ACCOUNT_ID>');
$pixel->read(array(AdsPixelsFields::CODE));

echo $pixel->{AdsPixelsFields::CODE}.PHP_EOL;
from facebookads.adobjects.adspixel import AdsPixel
from facebookads.adobjects.adaccount import AdAccount

account = AdAccount('act_<AD_ACCOUNT_ID>')
account.get_ads_pixels(fields=[AdsPixel.Field.code])
AdsPixel adsPixel2 = new AdsPixel(<PIXEL_ID>, context).get()
  .requestCodeField()
  .execute();
curl -G \
  -d 'fields=code' \
  -d 'access_token=<ACCESS_TOKEN>' \
  https://graph.facebook.com/v2.5/<PIXEL_ID>

The API will return the following, where the code parameter contains the relevant Custom Audience Pixel code:

{
  "data": [
    {
      "code": "<script>(function() {\n  var _fbq = window._fbq || (window._fbq = []);\n  if (!_fbq.loaded) {\n    var fbds = document.createElement('script');\n    fbds.async = true;\n    fbds.src = '//connect.facebook.net/en_US/fbds.js';\n    var s = document.getElementsByTagName('script')[0];\n    s.parentNode.insertBefore(fbds, s);\n    _fbq.loaded = true;\n  }\n  _fbq.push(['addPixelId', '11111']);\n})();\nwindow._fbq = window._fbq || [];\nwindow._fbq.push(['track', 'PixelInitialized', {}]);\n</script>\n<noscript><img height=\"1\" width=\"1\" alt=\"\" style=\"display:none\" src=\"https://www.facebook.com/tr?id=11111&amp;ev=NoScript\" /></noscript>", 
      "id": "11111"
    }
  ], 
  "paging": {
    "cursors": {
      "before": "MjM4NzQ5Njk5NjI2Mzc2", 
      "after": "MjM4NzQ5Njk5NjI2Mzc2"
    }
  }
}
Facebook pixel reference

Create Audience

To create a custom audience from your website:

use FacebookAds\Object\CustomAudience;
use FacebookAds\Object\Fields\CustomAudienceFields;
use FacebookAds\Object\Values\CustomAudienceSubtypes;

$custom_audience = new CustomAudience(null, 'act_<AD_ACCOUNT_ID>');
$custom_audience->setData(array(
  CustomAudienceFields::PIXEL_ID => <PIXEL_ID>,
  CustomAudienceFields::NAME => 'My New Website Custom Audience',
  CustomAudienceFields::SUBTYPE => CustomAudienceSubtypes::WEBSITE,
  CustomAudienceFields::RETENTION_DAYS => 15,
  CustomAudienceFields::RULE => array('url' => array('i_contains' => 'shoes')),
  CustomAudienceFields::PREFILL => true,
));
$custom_audience->create();
from facebookads.adobjects.customaudience import CustomAudience

audience = CustomAudience(parent_id='act_<AD_ACCOUNT_ID>')
audience[CustomAudience.Field.name] = 'my audience'
audience[CustomAudience.Field.subtype] = CustomAudience.Subtype.website
audience[CustomAudience.Field.retention_days] = 15
audience[CustomAudience.Field.rule] = {'url': {'i_contains': 'shoes'}}
audience[CustomAudience.Field.pixel_id] = <PIXEL_ID>

audience.remote_create()
CustomAudience customAudience = new AdAccount(act_<AD_ACCOUNT_ID>, context).createCustomAudience()
  .setPixelId(<PIXEL_ID>)
  .setName("My New Website Custom Audience")
  .setSubtype(CustomAudience.EnumSubtype.VALUE_WEBSITE)
  .setRetentionDays(15L)
  .setRule("{\"url\":{\"i_contains\":\"shoes\"}}")
  .setPrefill(true)
  .execute();
curl \
  -F 'pixel_id=<PIXEL_ID>' \
  -F 'name=My New Website Custom Audience' \
  -F 'subtype=WEBSITE' \
  -F 'retention_days=15' \
  -F 'rule={"url":{"i_contains":"shoes"}}' \
  -F 'prefill=1' \
  -F 'access_token=<ACCESS_TOKEN>' \
  https://graph.facebook.com/v2.8/act_<AD_ACCOUNT_ID>/customaudiences

In order to create a Custom Audience using this method, the account needs to have already accepted the Terms of Service for Custom Audiences, which can be found in Power Editor.

The following custom audience params are most relevant for custom audiences from your website:

NameDescriptionTypeRequired

name

The name for the cluster.

String

Yes

subtype

Must be set to WEBSITE.

String

Yes

rule

Audience rules to be applied on the referrer URL.

string

Yes

retention_days

Number of days to keep the user in this cluster. You can use any value between 1 and 180 days. Defaults to 14 days if not specified.

Int

Yes

pixel_id

The pixel associated with this audience.

Int

Yes

prefill

true - Include website traffic recorded prior to the audience creation.
false - Only include website traffic beginning at the time of the audience creation.

Boolean

No

The API will return the id of the audience upon success.

Custom Audience reference

Audience Rules

A custom audience from a website must contain at least one audience rule. As of 2.8 you can only provide up to 200 comparison operators in a rule for an audience.

The supplied rules can be applied on either the referrer URL and/or specific events/data sent via the Tag API. The rules will decide whether the user should be added to this custom audience.

Rules are made up the following operators and data or events:

NameDescription

Operators

The type of filter.

i_contains

Contains substring (case insensitive)

i_not_contains

Does not contain substring (case insensitive)

contains

Contains substring (case sensitive)

not_contains

Does not contain substring (case sensitive)

eq

Equal to (case sensitive)

neq

Not equal to (case sensitive)

lt

Less than (numeric fields only)

lte

Less than or equal to (numeric fields only)

gt

Greater than (numeric fields only)

gte

Greater than or equal to (numeric fields only)

regex_match

Matches a regular expression (eg: "example\.com.*purchase$"). The full PCRE grammar is supported

Data

The data being filtered.

url

The full escaped URL of the site visited

domain

The domain of the site visited

path

The path of the site visited (not including the domain)

event

The name of the pixel event. Example: 'ViewContent'

device_type

The device the site was visited with. Available values:
desktop

mobile_android_phone

mobile_android_tablet

mobile_ipad

mobile_ipod

mobile_iphone

mobile_tablet

mobile_windows_phone

any customData field

Any field added to customData of a pixel firing. Examples: productId, category, price

Each rule is expressed as a JSON encoded string.

Example Rules

RuleDescription
{  
  "url": {  
    "i_contains": "shoes"  
  }  
}

will match all the referrer URLs containing the string shoes

{  
  "url": {  
    "i_not_contains": "shoes"  
  }  
}

will match all the referrer URLs not containing the string shoes

{
  "and": [
    {"event": {"i_contains": "ViewContent"}},
    {"price": {"gte": 100}}
  ]
}

this will match ViewContent events where the price of the item was greater than or equal to $100. Consider this rule against the following event:

_fbq.push([ 'track', 'ViewContent', { productId: 1234, category: 'Men > Shoes', price: 199 } ]);

{
  "or": [
    {"url": {"i_contains": "shoes"}},
    {"and": [
      {"event":{"i_contains":"ViewContent"}},
      {"category":{"i_contains":"shoes"}}
    ]}
  ]
}

this will match either referrer URLs containing the string shoes or ViewContent events where the category contains the string shoes

{
  "and": [
    {"url":{"i_contains":"shoes"}},
    {"url":{"i_contains":"type=25"}}
  ]
}

will match all the referrer URLs containing 'shoes' and 'type=25'

{
  "or": [
    {"url":{"i_contains":"shoes"}},
    {"url":{"i_contains":"boots"}}
  ]
}

will match all the referrer URLs containing either shoes or boots

{
  "and": [
    {"or": [
      {"url":{"i_contains":"shoes"}},
      {"url":{"i_contains":"boots"}}
    ]},
    {"or": [
      {"url":{"i_contains":"mybrand"}},
      {"url":{"i_contains":"otherbrand"}}
    ]}
  ]
}

will match all the referrer URLs containing at least one of shoes or boots, AND at least one of 'mybrand' or 'otherbrand'