Setting userid in wordpress

Hi there

I am hoping someone can help me please.

I have a wordpress site where I want to track logged in users.

I’m attempting to do this via the UserID in Piwik and I’ve added the following into the tracking script (after the line that says: var _paq = _paq || []; )

_paq.push([‘setUserId’, ‘<?php global $piwikuserid;
if ( is_user_logged_in() ) {
$current_user = wp_get_current_user();
$piwikuserid = $current_user->user_login;
} else {
$piwikuserid = “visitor555”;
}
echo $piwikuserid;
?>’]);

However, once I make the above change it doesn’t track anything at all.
Can anyone please assist ? I am sure that the php code itself is correct.

I’ve also tried the following which also doesn’t work.

<?php global $piwikuserid; if ( is_user_logged_in() ) { $current_user = wp_get_current_user(); $piwikuserid = $current_user->user_login; } else { $piwikuserid = "visitor555"; } echo sprintf("_paq.push(['setUserId', '%s']);", $piwikuserid); ?>

@zunaidk, you ever get this working? I’m trying to do the same thing right now.

Figured this out by following the docs. Added this to my footer script:

<?php
global $current_user;
?>
<!-- Piwik -->
<script type="text/javascript">
  var _paq = _paq || [];
 <?php 
 // If used is logged-in then call 'setUserId' 
// $userId variable must be set by the server when the user has successfully authenticated to your app.
if (isset($current_user->ID)) {
     echo sprintf("_paq.push(['setUserId', '%s']);", $current_user->ID);
}
 ?>
//Set Any other custom variables here
</script>

If you are using Wordpress and want to use Piwik for tracking, then you don’t need to add any custom code for this.
You can just download the wp-Piwik plugin and activate it.
now login to your website/wp-admin and click on “wp-Piwik” from the settings menu.
now "Connect to Piwik tab and select Self-hosted(PHP API)
now you need to get the auth token from Piwik
for that just log in to Piwik and plateform->API then under “user authentication” copy the alphanumeric string, that is your auth key.
now in wp click on auto config checkbox and save.
now you can just “Enable Tracking”.

To avoid any kind of malfunctioning, I would suggest you create a Backup of your WordPress first (How to fully backup your WordPress).

Thanks