Custom Audiences from Your Website

Create a custom audience of users who visited or took specific actions on your website using Facebook Pixel, JavaScript Tag API, and audience rules. See Custom Audience, Targeting', Facebook Tag API, Facebook Pixel Stats, Website Custom Audiences with Facebook Pixel.

Once you create a custom audience with website data, reference it in ad targeting as you do with standard custom audiences. Facebook automatically updates this audience based on the retention policy you setup.

Code samples and rules below show old website custom audience pixel code, however you should upgrade to Facebook pixel. See Website Custom Audiences with Facebook Pixel.

Create the Pixel

The following API call can be used to create a Custom Audience Pixel.

use FacebookAds\Object\AdsPixel;
use FacebookAds\Object\Fields\AdsPixelFields;

$pixel = new AdsPixel(null, 'act_<AD_ACCOUNT_ID>');
$pixel->{AdsPixelFields::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.10/act_<AD_ACCOUNT_ID>/adspixels

This returns the pixel ID:

{
  "id": "11111"
}

Read the Pixel Code

Then retrieve the Custom Audience Pixel code:

use FacebookAds\Object\AdsPixel;
use FacebookAds\Object\Fields\AdsPixelFields;

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

echo $pixel->{AdsPixelFields::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.10/<PIXEL_ID>

This returns the following, where code 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"
    }
  }
}

Create Audience

To create a Custom Audience using this method, the account needs to have already accepted the Terms of Service for Custom Audiences, in Power Editor:

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.adaccount import AdAccount
from facebookads.adobjects.customaudience import CustomAudience

ad_account = AdAccount(fbid='act_<AD_ACCOUNT_ID>')
audience = ad_account.create_custom_audience(params={
    CustomAudience.Field.name: 'My New Website Custom Audience',
    CustomAudience.Field.subtype: CustomAudience.Subtype.website,
    CustomAudience.Field.retention_days: 15,
    CustomAudience.Field.rule: {'url': {'i_contains': 'shoes'}},
    CustomAudience.Field.pixel_id: <PIXEL_ID>,
})
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.10/act_<AD_ACCOUNT_ID>/customaudiences

These parameters 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

This returns the id of the audience upon success.

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 rules are applied on either the referrer URL or specific events and data sent via Tag API. Rules determine whether someone should be added to this custom audience.

Rules have 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 such as "example\.com.*purchase$". The full PCRE grammar is supported

Data

Data being filtered.

url

Fully escaped URL of the site visited

domain

Domain of site visited

path

Path of site visited, excluding domain

event

Name of pixel event, such as 'ViewContent'

device_type

Device that accessed site:
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 for pixel fires, such as productId, category, price

Provide each rule as a JSON encoded string.

Example Rules

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

Match all referring URLs containing the string shoes

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

Match all referring URLs not containing the string shoes

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

Match ViewContent events where item price is greater than or equal to $100. Consider using this rule for 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"}}
    ]}
  ]
}

Match either referring URLs containing the string shoes or ViewContent events where category contains the string shoes

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

Match all referring URLs containing 'shoes' and 'type=25'

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

Match all referring 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"}}
    ]}
  ]
}

Match all referring URLs containing at least one of shoes or boots, AND at least one of 'mybrand' or 'otherbrand'


Enhanced Website Custom Audiences

This a new feature that is not yet available to all advertisers. Please report bugs and provide feedback to your technical contact. Currently you may only create 20 Enhanced Website Custom Audiences per ad account.

This introduces additional flexibility to create custom audiences. You can now create targeting rules from aggregate behavior, device type and dynamic date, which is in beta. For background, see Website Custom Audiences with Custom Audience Pixel.

Editable Fields

The rule_aggregation and retention_days are editable fields. However, editing rule_aggregation and retention_days won't flush the audience, meaning that people who only match the old rule/aggregation would continue to be in the audience until they expire.

Aggregate Functions

Create custom audiences based upon the frequency and intensity of behavior using the rule_aggregation field. With this, you define an aggregate function. For example:

 rule_aggregation={"type":"sum", "config":{"field":"price"}, "operator":">", "value": "100"}

Aggregation rules are made up the following fields:

NameDescription

type

The type of the aggregation function: count, sum, avg, max, min, time_spent, last_event_time_field.

config

Required by certain types of aggregation functions.

operator

  • =
  • >
  • >=
  • <
  • <=
  • !=
  • @> - Time between delivery time and time passed by the pixel is longer than the value. Namely, now - pass-in-time > value.
  • @< - Time between delivery time and the time passed by the pixel is shorter than the value: now - pass-in-time < value.

value

Integer. Units for time_spent and last_event_time_field are seconds.

The available functions are:

NameRequired ConfigDescription

count

Number of pixel fires that satisfy the rule, such as url contains Purchase.

sum

{“field”: “field_name”}

Accumulate values of the specified field sent by pixel events.

avg

{“field”: “field_name”}

Average value of specified field sent by pixel events.

max

{“field”: “field_name”}

Maximum value of specified field sent by pixel events.

min

{“field”: “field_name”}

Minimum value of the specified field sent by pixel events.

time_spent

Total time spent in seconds on URLs that satisfy the rule.

last_event_time_field (beta)

{“field”: “checkin_date”, “time_format”: “YYYY-MM-DD”}

Used in dynamic date rules. The value of the specified field must be a valid time in the specified time format. For example, in this case, time format is YYYY-MM-DD, so {checkin date: 2015-08-28} is valid but {checkin date: 20150828} is invalid.

Examples

All website visitors in the past 30 days, who visited more than 5 times:

curl \
-F "name=visit_more_than_5_times_in_30_days" \
-F "pixel_id=<PIXEL_ID>" \
-F "subtype=WEBSITE" \
-F "retention_days=30" \
-F 'rule={"url":{"i_contains":"&lt;url>"}}' \
-F 'rule_aggregation={"type":"count", "operator":">", "value": "5"}' \
-F "access_token=<ACCESS_TOKEN>" \
"https://graph.facebook.com/<API_VERSION>/act_<AD_ACCOUNT_ID>/customaudiences"  

All website visitors who spent more than 5 minutes in past 180 days on your website:

curl \
-F "name=spent_more_than_5_mins_in_180_days" \
-F "pixel_id=<PIXEL_ID>" \
-F "subtype=WEBSITE" \
-F "retention_days=180" \
-F 'rule={"url":{"i_contains":"&lt;url>"}}' \
-F 'rule_aggregation={"type":"time_spent", "operator":">", "value": "300"}' \
-F "access_token=<ACCESS_TOKEN>" \
"https://graph.facebook.com/<API_VERSION>/act_<AD_ACCOUNT_ID>/customaudiences"

Users who spent more than $500 on your website in the last 30 days:

curl \
-F "name=spent_more_than_$500_in_30_days" \
-F "pixel_id=<PIXEL_ID>" \
-F "subtype=WEBSITE" \
-F "retention_days=30" \
-F 'rule={"and": [
{"event": {"i_contains": "purchase"}},
{"currency": {"eq": "USD"}}
]}' \
-F 'rule_aggregation={"type":"sum", "config":{"field":"price"}, "operator":">", "value": "500"}' \
-F "access_token=<ACCESS_TOKEN>" \
"https://graph.facebook.com/<API_VERSION>/act_<AD_ACCOUNT_ID>/customaudiences"

Users who spent at least $100 in one transaction in last 30 days:

curl \
-F "name=spent_at_least_$100_in_one_session_in_30_days" \
-F "pixel_id=<PIXEL_ID>" \
-F "subtype=WEBSITE" \
-F "retention_days=30" \
-F 'rule={"and": [
{"event": {"i_contains": "purchase"}},
{"currency": {"eq": "USD"}}
]}' \
-F 'rule_aggregation={"type":"min", "config":{"field":"price"}, "operator":">", "value": "100"}' \
-F "access_token=<ACCESS_TOKEN>" \
"https://graph.facebook.com/<API_VERSION>/act_<AD_ACCOUNT_ID>/customaudiences"

Users who made 3 or more purchases in the last 30 days:

curl \
-F "name=3_or_more_purchases" \
-F "pixel_id=<PIXEL_ID>" \
-F "subtype=WEBSITE" \
-F "retention_days=15" \
-F 'rule={"event":{"i_contains":"purchase"}}' \
-F 'rule_aggregation={"type":"count", "operator":">=", "value": "3"}' \
-F "access_token=<ACCESS_TOKEN>" \
"https://graph.facebook.com/<API_VERSION>/act_<AD_ACCOUNT_ID>/customaudiences"

Device Type Targeting

Enhanced Website Custom Audiences introduces the ability to create targeting based upon device type a website is visited from. The supported device types are:

  • desktop
  • mobile_android_phone
  • mobile_android_tablet
  • mobile_ipad
  • mobile_ipod
  • mobile_iphone
  • mobile_phone
  • mobile_tablet
  • mobile_windows_phone

Examples

Android Users:

curl \
-F "name=android_users" \
-F "pixel_id=<PIXEL_ID>" \
-F "subtype=WEBSITE" \
-F "retention_days=180" \
-F 'rule={
  "or":[
    {"device_type":{"eq":"mobile_android_phone"}},
    {"device_type":{"eq":"mobile_android_tablet"}}
  ]
}' \
-F "access_token=<ACCESS_TOKEN>" \
"https://graph.facebook.com/<API_VERSION>/act_<AD_ACCOUNT_ID>/customaudiences"

Desktop Users:

curl \
-F "name=mobile_visitors" \
-F "pixel_id=<PIXEL_ID>" \
-F "subtype=WEBSITE" \
-F 'rule={"device_type":{"eq":"desktop"}}' \
-F "access_token=<ACCESS_TOKEN>" \
"https://graph.facebook.com/<API_VERSION>/act_<AD_ACCOUNT_ID>/customaudiences"