PieterB
PieterB

Reputation: 140

Code to attach filter to profile

I'm looking for example code to attach a filter to a Google Analytics Profile. I've added the filter to an account, which works great. But I can't find code to attach it to a certain profile.

I have looked at the source of the php api client, and see the management_profileLinkFilter, but I don't understad what which variables I need.

Upvotes: 1

Views: 127

Answers (1)

PieterB
PieterB

Reputation: 140

After a few hours of testing, trail and error it finally works!

First, use both the ANALYTICS and ANALYTICS_EDIT to the scope. Then use the following code:

        // Construct the filter expression object.
    $details = new Google_Service_Analytics_FilterExpression();
    $details->setField("GEO_DOMAIN");
    $details->setMatchType("EQUAL");
    $details->setExpressionValue("example.com");
    $details->setCaseSensitive(false);

    // Construct the filter and set the details.
    $filter = new Google_Service_Analytics_Filter();
    $filter->setName("Exclude example.com");
    $filter->setType("EXCLUDE");
    $filter->setExcludeDetails($details);
    $filterResult = $analytics->management_filters->insert($accountId, $filter);

    // Construct the filter reference.
    $filterRef = new Google_Service_Analytics_FilterRef();
    $filterRef->setAccountId($accountId);
    $filterRef->setId($filterResult->getId());

    // Construct the body of the request.
    $body = new Google_Service_Analytics_ProfileFilterLink();
    $body->setFilterRef($filterRef);

    $analytics->management_profileFilterLinks->insert($accountId, $propertyId, $profileId, $body);

Upvotes: 1

Related Questions