Upcoming LunaMetrics Seminars
New York City, Aug 4-8 San Francisco, Aug 11-15 Los Angeles - Anaheim, Sep 8-12 Washington DC, Sep 22-26

Stuff More Than One Value into GA’s User Defined Segment





The User Defined Segment Variable in Google Analytics allows us to give each visitor to a site a distinctive label. Member or Non-member, Male or Female, Large or Small. This value is then stored in a cookie called __utmv on the visitors computer. Each time the visitor comes to your site, the Tracking Code checks for a value in that cookie and sends it along with the rest of the data.

The More-Than-One-Value Problem

But sometimes you would like to keep track more than one piece of information in GA’s User Defined Segment. You might want to know when you have a Small Female Non-member or a Large Male Member.

Most of you already know that Google Analytics only gives us one User Defined Variable. At first glance, that isn’t an issue, we can just set our variable to ‘Small/Female’ and now we have more than once piece of information about that visitor, right?

But you don’t always learn every piece of information at the same time. And whenever you set the value of the variable, it overwrites the previous value.

Here is a technique (and the JavaScript) that I have used when I’ve needed to overcome this particular limitation.

How it Works

With the old version of the Tracking Code using urchin.js, we set the variable with:

_utmSetVar('someValue');

And in the new version using ga.js:

pageTracker._setVar('someValue');

But instead of using those, we’re going to use a new function:

superSetVar('someValue');

This function will check to see if the visitor already has ‘someValue’ assigned. If the value is already there, the function doesn’t do anything. But if it is not there, it adds this value to the end.

For example, if we set two values in a row with superSetVar:

superSetVar('/eyes=blue');
superSetVar('/hair=blonde');

instead of the second value overwriting the first, and making the User Defined Segment Variable equal to ‘/hair=blonde’, with superSetVar it is equal to ‘/eyes=blue/hair=blonde’.

In this way, we can use the superSetVar function whenever we need to add a piece of information to the User Defined Segment Variable in the __utmv cookie, and each time, the new value gets added to the end.

Naming Conventions

hello-my-name-isThis brings us to some naming conventions. You’ll notice that I’m using the format /name=value for my variables. Aside from helping us visually in the GA reporting interface, and giving us a little something extra to work with when setting up filters, it also assists us in our next task – unsetting a value.
[This naming convention is required in order for everything to work as advertised. However, feel free to alter the code within the super_set_var.js to suit your own needs.]
With the original GA functions, we don’t need to unset our variable, since every time we set a value, it overwrites the previous value — a sort-of built-in unset. So if you have a value of NonMember and later become a Member, the NonMember values gets overwritten and you just end up with ‘Member’. But if you used superSetVar you would end up with something like /status=nonmember/status=member.
Because of this we need to have another function, unSetVar. You could use it like this:

unSetVar('/status=');
superSetVar('/status=member');

The unSetVar finds any instance of ‘/status=something’ and deletes it. So if you wanted to change someone’s eye color:

unSetVar('/eyes='); // clears all /eyes=someColor
superSetVar('/eyes=green'); // adds '/eyes=green' to the end of the __utmv cookie

What value will show up in the reporting interface?
Sometimes figuring out what you’re going to see in the reporting interface is a little tricky. With this method of setting the User Segment Variable, it should work like this:
If the visitor does not have a value already defined, then the first value that you give them will be used.
This means that if you call superSetVar multiple times, the latter values won’t show up, until the user comes back for another session.
However, if the visitor already has a value for the User Defined Segment Variable when they arrive at your site, then that value will be used. If you set additional values, they won’t show up in the GA Reporting Interface until the users next session.

Implementation:

1. Download super_set_var.js

2. Copy it to your web server.

3a. For the new version of the GATC, add the line in bold to your GATC after the call to ga.js, making sure to change the /path/to/super_set_var.js to the location on your webserver where you put that file in step 2:
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript" src="/path/to/super_set_var.js"></script>
<script type="text/javascript">
var pageTracker = _gat._getTracker("UA-xxxx-y");
. . .
</script>

3b. For the old version of the GATC:
<script src="http://www.google-analytics.com/urchin.js"
type="text/javascript"></script>
<script type="text/javascript" src="/path/to/super_set_var.js"></script>
<script type="text/javascript">
_uacct = "UA-12345-1";
. . .
</script>

4. Use superSetVar(“/someName=someValue”); wherever you would have used pageTracker._setVar(“someValue”); or _utmSetVar(“someValue”);

Technical Note:
This implementation chooses to set the __utmv cookie with a pageTracker._setVar(‘…’); that is associated with a ‘fake’ UA number. You could instead choose to alter the code to write the cookie by hand, or to use a _setVar(‘…’); that is associated with the actual UA number for the account.

If you have any comments, improvements, alternatives, etc, please post them below. I’m sure some of you have had the opportunity to do this before, so share any pitfalls you’ve encountered or just tell me why your method is better than mine.

-John

http://www.lunametrics.com/blog/2008/04/17/stuff-more-than-one-value-in-gas-user-defined-segment/

31 Responses to “Stuff More Than One Value into GA’s User Defined Segment”

I like this solution, but is had some disadvantages. I want to track someone’s search behaviour with this solution. The main search function has 3 pulldown menu’s, and I want to know which options are used most.

The pulldowns have 50, 50 and 20 options, that makes 50.000 combinations. And with the 500 rows max export function I can’t report all of them. Right now I created 3 different profiles that track each pulldown separately, that works slightly better except from the fact that I can’t combine that info easy.

Reallly good solution John!
I used to to do this dirty stuff job only with filters, but, reading cookies was the next step…
But, this solution works with multiple-domains implementations? this cookie-reading function works when combined with setDomainName “none”, or, even, cookiePath attribution?
Thanks!
Best,
Leo Naressi

John says:

Leonardo,

As it is, it doesn’t account for setting the domain name or cookie path, and just uses the default of the full domain name. This is something I should have covered in the post. You have a few options. You can alter the super_set_var.js file to set the domain name and cookie path to what you are using. For example:

var superSetVarTracker = _gat._getTracker(“UA-1-1″); // set up a tracker to call _setVar from
superSetVarTracker._setDomainName(‘domain.com’);
superSetVarTracker._initData();
superSetVarTracker._setVar(newVar); // call _setVar with the new value

An alternative is instead of using this fake UA number and separate tracker, just use whatever tracker is already defined. in which case instead of the above, you would just have something like

pageTracker._setVar(newVar);

Doing that would automatically take into account what your domain was set to or what cookie path you were using.

Sorry for any confusion there.

Winston says:

Any idea how to populate user defined variable through the url?

For instance, http://some…site.com/?utm_campaign=This+one&utm_userdefined=That+one

Could parse the url values and call the setVar function, just wondering if there’s a more efficient way..

Cheers,
Winston

Good Work John! It inspired me a lot.

And Winston, You have read my mind!
Populate user defined trough URL is a good way to handle specific situations.
It´s not so hard to do, just iterate the parameters and using the superSetVar to add the variables…

Good Luck, soon i will try this too…

Best,
Leonardo

Gom says:

This is a nice workaround for most situations and I applaud the creativity. Sadly, it won’t work for me–I think, for a number of reasons. First, if a visitor acquires seg1 and seg2 in reverse order, he or she will end up on a different row. This issue can be avoided only by elaborate unsetting and resetting every time. Second, a single concatenated visitor segmentation parameter means I can only have one ranking of segments, top being first. If I choose the top level to be registered vs. unregistered, and then buyers vs. non-buyers, I will not be able to see, e. g., buyers/registered vs. buyers/unregistered. Of course, all of these “issues” I’m listing are limitations of GA as of now, and don’t have anything to do with John’s work. Cheers!

John Henson says:

Gom,

1. They will end up in different rows. It would not be horrible to modify the code to put every thing in the same order though. Certainly possible to do. On the other hand, even though they are in different rows in the report, the data is still there. You can pull that data into excel and do the analysis there. It is not ideal, but also not so cumbersome to prevent someone from using the data to make business decisions if that is what is needed.

2. I think the same things apply to number two. In your example, you would end up with:
/buyer=true/registered=true (buyers/registered from your example)
/buyer=true (buyers/unregistered from your example)
And then you could compare those two segments. (the first set could be in reverse order so you would have to do some hand work)

The User Defined Segment Variable is very limiting in GA. I would love to see the addition of some extra variables as well as changes in the behavior and how a session is attributed a variable. For example, I would like to see a session matched with the Last variable that was set, instead of with the first.

Let me know if any of that helps, or if I misunderstood anything.

John

Werner says:

Hi John, First, let me say that this is a very helpful article which I read right after it was posted. Thank you again! Although there are more recent articles I think this one might be the best context for my question.

I’m thinking about a smart way to add the first source (e.g. Affiliate, msn organic) of a visitor in a way that “sticks” all along.

Here’s an example. 1. A visitor comes the first time to a site via AdWords, neither converts or buys, but remembers the name of the website. 2. The next day the visitor searches for the site name in google, clicks on an organic result, gets to the site and buys (yeah!). Cookie setVar (and other GA and AdWords-Cookies) will tell us that the ecommerce was executed by somebody from msn organic.

Of course you can send the AdWords traffic to a special landing page and set setVar there. Possible, but means some work which also has to be done for Affiliates, etc. Is there another – and smarter – way?

Cheers
Werner

John Henson says:

Werner,

I think this is what you are describing:

On every page of your website, check to see if there is a utmv cookie.

If not, then pageTracker._setVar(*REFERRER*);

If there is, Do Nothing.

Werner says:

Thank you a lot for your prompt reply, John.

Exactly. This is the case if setVar-Cookie is not used yet. A solution for this case would help a lot. Any idea?

In case setVar would already be in use (e.g. to separate registered users from customers) it would be a bid more comprehensive:

IF a visitor has not setVar-Cookie (at all) yet, set a setVar-Cookie that includes the value for the referrer (as above).

IF a visitor has a setVar-Cookie already, but without a value for the referrer, add the value for the referrer into the (existing) setVar-Cookie.

IF a visitor has a setVar-Cookie already that contains a value for the referrer, do nothing.

To the background: there is a high number of traffic from organic search using the company’s name (although it’s a niche market and such the company name is no generally known brand, like e.g. BMW). On the other side: (as always) a part of the PPC-campaigns is on a borderline regarding ROI. So I wonder how many (future) customers the page wins via PPC (e.g. PPC-campaigns which address users in an early phase of their search behaviour), that do not show up in E-Commerce tracking as PPC, as these visitors are using organic search for their returning visits and such are reported as E-Commerce from organic search. Basing on the GA reports you might be tempted to shut down some PPC campaigns (running on negative ROI) although – basing on better information – they would be profitable. This just as an example, of course there would be more insight for the information about the initial source of the visitor.

John Henson says:

“IF a visitor has a setVar-Cookie already, but without a value for the referrer, add the value for the referrer into the (existing) setVar-Cookie.”

If they already have a cookie, then it is not their first visit, therefore you are not capturing their original referrer which was your goal. And you will have inconsistent data.

I would go with my initial algorithm. You are only able to capture initial referrer information if they are a new visitor. Even with my simpler algorithm, you will encounter some data inconsistency, but it will be less.

Also keep in mind that the very first value of the __utmv cookie that is seen by GA on any given visit is the one that will be attached to that visit, even if the value is changed within the course of that visit.

Of course, you could also do it just the way you described if you’re ok with that data. The key is to understand how GA handles the data so you know what you’re going to get on the other end. There is no right or wrong, as long as the numbers on the reporting side are not mis-understood.

You could use the code that I have in this post to do exactly that.

You have permission to use and modify that code however you want. Though, it shouldn’t require much modification — just some additional JavaScript to handle the setting of the /referrer=xxxxx name-value pair.

Werner says:

Thank you again and a lot for your response John.

Regarding capturing the first visit: you’re right.

If I may bug you one more time: where would you take the referrer-value: rather from the browser or as a readout of __utmz?

John Henson says:

I think that would be mostly personal preference. Google Analytics gets the referrer value from the browser and just writes it to the __utmz cookie. I would probably just get it from the browser, personally.

Matt Biskup says:

I’d like to group all my traffic into Paid or Free segments so I could work with GA charts on each of these two big segments. Reason: I have clients with paid inclusion in Yahoo which shows up as Organic in GA, and I have a client that we use utm_Medium=email for their house email to their existing lists (free) as well as email where we are paying to have a banner included in some other business’ blast so this mass Paid or Free segmentation would help. I can do this with filters but I wind up subtracting all Visits/Visitors/Transactions, etc… tallied by my “All Paid Sources” Profile from the main Profile which has no filters.

How would I populate _setVar to do this? Would I use the regular code or the SuperSetVar code? I’m not a programmer but I’d like to go into my IT dep’t with at least something in my hand that says they could do this – saves me from calling b.s. on my IT guy if he doesn’t know it can be done but tells me it “can’t” anyway.

Thanks,
Matt Biskup

John Henson says:

The best way to handle those 2 problems is with more descriptive campaign tagging.

Is it possible to tag your Yahoo paid search with campaign parameters that include utm_medium=cpc ?

Is it possible to tag your Paid email campaigns with utm_medium=emailp or some other value that is different from “email” ?

In order to use the user defined segment you have to know that the visitor came from one of these sources anyway, that means that the links would already have to be tagged with some other identifier. Otherwise you’d not have any hook with which to set the user defined segment for that visitor. That is to say, it doesn’t seem like you’d be able to tell which visitors came from yahoo paid search and which came from yahoo organic search.

asdsa says:

*Large Male Member* <– that’s an unfortunate wording :D

John Henson says:

Asdsa,

You are the first person to comment on that !!

Daniel says:

Hello John and thanks for posting this solution.

I would like to know if your solution can work for me, or what can be done if not.
I am advertising a minisite where people register, during their registration I gather information about them and whether they completed successfully of failed.
I would like to use the user defined segment to do some drill downs, but I have that information DURING and at THE END of the process.
I understood from the talkbacks that this information will only be posted at the next visit.

Is there a way to track information about the user as part of the current session?

Would appriciate suggestions.

Thanks,
Daniel

Marissa says:

Thanks for this script – we’ve been trying to think of a way to lump a group of users together over time based on some of the actions they take on our site, and this seems to do the trick.

The only issue I’m having, is that the session appears to only be set on the return visit, and not on the visit where the action is taken. So let’s say I want to track users who sign up for our email list and then sign our petition:

1. On their first visit, they signup for the email list – in analytics, their user defined variable for this visit not set.
2. On their second visit, they sign the petition – their user defined variable for this visit is emailsignup=1
3. They would need to visit a third time in order to get the user defined variable emailsignup=1/petition=1

Is there any way around this? I know Google Analytics is picky when it comes to resetting user defined variables. Is there a more clear way to reset it within the session? Or is there Javascript I could use to do a force reset of the session to get the user defined variable in there?

Thanks!
Marissa

Hey John,

Nice script. Small and simple. We’re having some trouble integrating it though – it seems that if we try to unset the var and there’s only one in the cookie, it doesn’t get removed. For example,

superSetVar(“/eyes=blue”); // cookie says eyes = blue
unsetVar(“/eyes=”); // cookie still says eyes = blue

Debugging in Firebug I see it getting to superSetvarTracker._setVar(“”); but checking the cookie after this, it still has the original value.

Any ideas?

Thanks,
Rob.

Mitja Petan says:

Hi John,

Thank you for your code. But I found bug in it.

If you send information like this:
superSetVar(‘/campaign_name=External Adv.’);

Then this value will not be sent into GA. Problem is if you are sending value with dot.

I think problem is here:
removePrefix = /^.*\.(.*)/.exec(getVar);

Hi,

Labelling mij vistors works. Thanks for your free advise.

Greetz,

Ioptia.nl

Leonardo says:

Hi,

could you post how would this implementation be whith the async tag? The new version of G.A code ?
Please!

Thanks

John says:

This was done well-before the release of Custom Variables.

Now that Custom Variables are available they are a much better solution for keeping track of multiple values.

I’m not sure that it is worth revisiting this to update the syntax. However, the easy way to update any traditional syntax to the new async syntax is simply to wrap all the traditional code with:

var _gaq = _gaq || [];
_gaq.push(function () {
//Traditional lines of GA JavaScript go Here
//Line 2
//Line 3
//Etc
// without the preceding “//” characters
});

Hi there, am I right in thinking that user variable implementation on Google Analytics has changed since your post? I need to look into 1st click attribution due to an issue with one of my accounts, and am interested in your proposed solution. Has your idea on this changed since you posted? Many thanks.

John says:

Hi Mark,

The implementation hasn’t changed, but you just don’t need it anymore.

You now have 5 Custom Variables in GA, instead of the single User Defined Segment that this post works with.

This means that you no longer need to “Stuff” data into a single variable — you have 5 separate variables to work with when storing data.

http://code.google.com/apis/analytics/docs/tracking/gaTrackingCustomVariables.html

Gilles says:

I love playign with the advanced stuff of GA.

My developer is trying to persuade me to move to .net from PHP. I have always disliked the idea because of the expenses. But he’s tryiong none the less. I’ve been using WordPress on numerous websites for about a year and am anxious about switching to another platform. I have heard fantastic things about blogengine.net. Is there a way I can import all my wordpress posts into it? Any kind of help would be really appreciated!

Webmaster says:

You should talk to your developer about that, or maybe find a wordpress or blogengine user group.

cadeau says:

Hi my family member! I wish to say that this post is awesome, nice written and come with approximately all vital infos. I?d like to peer extra posts like this .