How to add analytics metrics in audience manager attributes?

Hello all,

I would like to understand what is the best practice to create new attributes in Audience Manager. Especially, our aim is to build audience based on user navigation such as : visited more than N pages in his session, average session duration greater than 5 minutes etc… unfortunately, I don’t have access to my analytics variable in audience manager. I believe I should create an attribute and a tag to populate this attribute but I have no idea how to create this tag properly (eg nb of pages view in a session).
Thanks in advance for your help.

Best,

Alexandre Biton.

Hi @Alexandre!

Performing this type of audience attribution in Audience Manager demands that you create your own system for managing your custom attributes. The logic that does that needs to be configured and/or coded in Tag Manager.

So what you want to basically be doing is counting some things using custom script, and submit your results to Audience Manager.

The case you mentioned is to base your audience on number of pages in the session. It may be intepreted differently - maximum number of pageviews in any session, or average number of the pageviews in the session throughout all sessions. In my answer I will assume the latter, and we can discuss some details later on :slight_smile: also this is the case I already have practice with.

Average number of pageviews in a session is a calculation. Very simple one, but still. You can’t perform custom calculations within Audience Manager itself, but you can do that using JavaScript in Tag Manager.

To calculate the average for given user continuously you need to have number of pageviews and number of sessions of a given user stored in their profile, and you need to be able to send it to visitor browser so your code in Tag Manager can perform the calculation and send its result back to user profile in Audience Manager.
You need to consider privacy-wise if this is something you want to do. If that is not the way you can go for - other are more complex as they are to re-attribute the profile data offline periodically, which is much more complex process that you need to have an environment to run in.

First you need to count the number of page views. This is easy to be done - you want to increment what we call a counter type of attribute, which you can easily increment. It is extensively described here: JavaScript API — Piwik PRO Analytics Suite 16.33 documentation but what you basically need to be doing is triggering such a tag once per pageview:

<script>
  ppms.am.api('updateAttributes', {
    pageviews_count: {
      "action": "add",
      "value": 1,
  	}
  });
</script>

In this case attribute to store the pageviews count is called pageviews_count. It will be created automatically upon first execution of the code, but you can also create it manually beforehand - just remember to set its type to numeric.

With this tag you just need to use standard “All page views” trigger or other suitable pageview trigger for your case. It will be executed with each page view, counting overall number of pageviews for given user.

Now, the sessions count. It’s similar, you just need another trigger that is fired once per session:

<script>
  ppms.am.api('updateAttributes', {
    sessions_count: {
      "action": "add",
      "value": 1,
  	}
  });
</script>

And in trigger you need to use this option:

Of course, first step to be able to work with ppms.am.api is to initiate the API in your Tag Manager. This is done by inclusion of custom script and is described here: JavaScript API — Piwik PRO Analytics Suite 16.33 documentation

This tag needs to be triggered before you start to use ppms.am.api, so my advice is to set it on “DOM ready” trigger.

With the above done, you should have session and pageview counts visible in the profiles. This is source data for your calculation, but those attributes alone can also be useful in setting up the audiences.

Now for the average calculation. First, you need to fetch the data of pageviews and sessions count that you saved in Audience Manager profile.
The way we usually suggest to handle the data is to transport it to dataLayer, as it makes it easy to use in Tag Manager Tags and Triggers.
Logic that handles this can be put in single tag along with the Audience Manager API initiation. Big part of that code is done for handling the case when there is no attributes saved in the profiles yet, as when user is entering the website for the first time, there is no profile created for given person yet. This imperfection may lead to inaccuracy in counting those averages, but only for those non-engaged users, that are usually bouncing. This could be perfected by utilising localStorage for example to temporarily store information about browsing, but this would increase complexity of the solution greatly. Creation of profile in Audience Manager takes just seconds, so in real world almost 100% of visitors should have the average calculated properly - saying from experience on around 50k of unique users traffic.

For the code to be able to fetch the attributes, you need to enable their availability in Public API. This can be done in configuration of specific attribute in Audience Manager:

The code to handle that would look like this:

<script>
    (function(a,d,g,h,b,c,e){a[b]=a[b]||{};a[b][c]=a[b][c]||{};if(!a[b][c][e]){a[b][c][e]=function(){(a[b][c][e].q=a[b][c][e].q||[]).push(arguments)};var f=d.createElement(g);d=d.getElementsByTagName(g)[0];f.async=1;f.src=h;d.parentNode.insertBefore(f,d)}})
    (window,document,"script","https://your-instance.piwik.pro/audiences/static/widget/audience-manager.api.min.js","ppms","am","api");

    ppms.am.api("create", "xxxxxxxx-your-website-id-xxxxxxx", "your-instance.piwik.pro");
  
	ppms.am.api('getAttributes',
        function(userAttributes){ppas_processUserAttributes(userAttributes)},
        ppas_processLackOfProfile()
    );

function ppas_processUserAttributes(userAttributes){
    if (userAttributes.attributes.pageviews_count == null || userAttributes.attributes.sessions_count == null){
      var update_object = {pageviews_count: 1, sessions_count: 1, pageviews_per_session: 1};
      if (userAttributes.attributes.pageviews_count != null){
        update_object.pageviews_count=userAttributes.attributes.pageviews_count;
      };
      if (userAttributes.attributes.sessions_count != null){
        update_object.sessions_count=userAttributes.attributes.sessions_count;
      };
      ppms.am.api('updateAttributes', update_object);
    };
    
    var attributes_event = userAttributes.attributes;
    attributes_event.event="AM_attributes_loaded";
    dataLayer.push(attributes_event);
  };
    
  function ppas_processLackOfProfile(){
    //console.log("no profile available in API");
  };
</script>

After executing it, you end up with counts available in the dataLayer. Next step is to set them up as Tag Manager variables, by their names:

AM_attributes_loaded event is posted when attributes are pulled from the API, so this is what you want to react to in your trigger to execute below tag. It would replace the earlier mentioned tag for counting pageviews - attributes are pulled on DOM ready of each page view, so pageview_count will be also performed with each page view, and you can perform multiple attribute updates in a single API call:

<script>
  var pageviews_per_session = (parseInt({{ Pageviews count }})+1)/parseInt({{ Sessions count }});
  ppms.am.api('updateAttributes', {pageviews_count: {
        "action": "add",
        "value": 1,
		},
        pageviews_per_session:pageviews_per_session.toFixed(1)
        });
</script>

And the trigger:

And that’s it! I know it may be pretty complex in the first place so let me know if you have any doubts or questions. There are multiple parts to it so I hope I didn’t miss anything :sweat_smile: I hope this will allow you to advance in your solution. I will be happy to hear any feedback you might have, or whether you are happy with how the solution works :slight_smile:

The other case you mentioned - time in the session - can also be addressed in a similar way, either by just updating the attribute on 5 minutes mark. Tag Manager allows to react to time on given page view, so counting time of the session would demand performing additional logic using custom timestamp. Let us know if you would like to pursue that, then I could provide some example.

1 Like

Thank you for this very complete feedback. Will try to set that up on monday to avoid putting things live on a matchday :slight_smile:
Will reach out in case I face any issue.

Thank you again!

AB.