Custom variables

I want to use custom variables similar to the Piwik documentation tracking visitors as either logged in or anonymous.

Due to php template design, I have the Piwik code on all my pages; pages for logged in users use the visitors variable with logged in and pages open for everyone use the variable visitors with anonymous. This works well until a user logs out or visits as page which is for everyone. Therefore the logged in variable get replaced with anonymous.

I wondered how can I set up the code so loggedin takes priority over anonymous? I had this idea but am unsure of how what to code…

I could check to see if this is the user’s first visit and if for example the piwik session does not exist then record the visit as anonymous but when they log in record the visit as logged in. I can do all this with php but do not know how to check the first page -what session variable does piwik set when a user visits?

use setCustomVariable with scope ‘visit’

then do NOT send the variable if user is not logged in and only send it when logged in