• Hi,
    I’m trying to use a Tag Manager tracking code (“Tag Manager” under “Matomo Analytics” > “Settings” > “Add Tracking Code”) and track the User ID at the same time (“WP User ID” under “User ID Tracking”).

    I have my container set up with a Tag, a DOM Ready Trigger & a Matomo Configuration Variable and working, but user IDs are not tracked. The User ID is empty under the Variable, so I looked into filling it as advised in https://matomo.org/faq/tag-manager/how-do-i-set-the-user-id-using-matomo-tag-manager/.

    However, I noticed the user ID is not pushed to the MTM data layer in the generated code:

    
    <script>
    window._paq = window._paq || []; window._paq.push(['setUserId', '1']);
    var _mtm = _mtm || [];
    _mtm.push({'mtm.startTime': (new Date().getTime()), 'event': 'mtm.Start'});
    var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
    g.type='text/javascript'; g.async=true; g.src="https://domain.tld/wp-content/uploads/matomo/container_ID.js"; s.parentNode.insertBefore(g,s);
    </script>
    

    It seemed something like below would be more appropriate, so that it’s possible use the a {{uid}} variable in the tag manager:

    
    <script>
    window._paq = window._paq || []; window._paq.push(['setUserId', '1']);
    var _mtm = _mtm || [];
    _mtm.push({'uid':'1' });
    _mtm.push({'mtm.startTime': (new Date().getTime()), 'event': 'mtm.Start'});
    var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
    g.type='text/javascript'; g.async=true; g.src="https://domain.tld/wp-content/uploads/matomo/container_ID.js"; s.parentNode.insertBefore(g,s);
    </script>
    

    So I tried to check the available filters – I found matomo_tracking_code_script that looked promising, and I thought about using it to replicate what’s done with TrackingCodeGenerator::apply_user_tracking, but unfortunately it’s not called by TrackingCodeGenerator::prepare_tagmanger_code, it’s only called in TrackingCodeGenerator::prepare_tracking_code.

    I think pushing this the User ID to the MTM layer and, at the very least, adding a filter similar to matomo_tracking_code_script in TrackingCodeGenerator::prepare_tagmanger_code would be a huge improvement, and increase code architecture consistency.

    Please let me know if I’m wrong, but I feel that right now the only alternatives are either to manually change the tracking code to include both “Default Tracking” and “Tag Manager”, or to somehow output the user ID somewhere in the DOM and get it in Matomo Tag Manager, which to me is a solution that adds unnecessary coupling for the latter, and is far from straightforward in either case.

Viewing 8 replies - 1 through 8 (of 8 total)
  • Plugin Author Thomas

    (@tsteur)

    Hi @frogerme

    pushing the userId to the data layer, and configuring a userId variable for this and using this userId variable in the Matomo Configuration for the user ID would be definitely the best/right way to do this.

    Something like below should work:

    
    add_action('wp_head',function () {
     echo "<script>var _mtm = _mtm || [];_mtm.push({'uid':'". esc_js($userId) . "' });</script>";
    }, 9)
    

    I haven’t tested this but would assume this should work. I think you were already on the right track. It’s just that you don’t have to listen to a Matomo event to add the user ID. You could also listen to the wp_head event and then it should work too. Could you give this maybe a try?

    Thread Starter Alexandre Froger

    (@frogerme)

    Hi @tsteur !
    Thank you for the quick answer!

    I did manage to get the Tag Manager tracking working in a similar fashion (using a filter and adding a DOM element instead – simply a different datasource).

    The issue remains in terms of coupling though – it’d be cleaner to simply have it out of the box, because integrating it with glue code like so is counterintuitive, specially because tag manager is supposed to make adding snippets easier as outlined in the various tutorials ; the admin settings interface is asking what User ID to track, it is available when tracking with the default option, seemingly available with Tag manager according to the WP Admin interface, and yet the User ID is not tracked when it’s set with Tag Manager.

    For the reason above, I hesitate to mark the issue as resolved, because this sort of friction for plugin users is far from trivial IMO.

    Thread Starter Alexandre Froger

    (@frogerme)

    I think I found a related issue that’s somehow as critical: Ecommerce events are not tracked using the “Tag Manager” option under “Add Tracking Code”.

    It seems to me that’s because calling the AjaxTracker/MatomoTracker in the background instead of directly in the browser, it’s detected as a bot visit. Indeed, the string WordPress is a match in bots.yml. I made some error_log manual tests to confirm, and WordPress/5.8.2 gets matched. I would want to keep bots exclusion like most users, but it seems not compatible with current exclusion rules.

    I believe a way to fix this would be by either adding glue code like in non-WordPress tutorials (which somehow reduces the value of using the plugin), edit plugin core files (bad), or to include both “Tag Manager” and “Default tracking” codes manually (redundant and inelegant). I have yet to test any of these, but it seems less than straightforward.

    Trace:

    
    1638957566: Current datetime: 2021-12-08 09:59:26
    1638957566: Executing Piwik\Plugins\CoreHome\Tracker\VisitRequestProcessor::manipulateRequest()...
    1638957566: Executing Piwik\Plugins\IntranetMeasurable\Tracker\RequestProcessor::manipulateRequest()...
    1638957566: Executing Piwik\Plugins\Actions\Tracker\ActionsRequestProcessor::manipulateRequest()...
    1638957566: Executing Piwik\Plugins\Goals\Tracker\GoalsRequestProcessor::manipulateRequest()...
    1638957566: Executing Piwik\Plugins\Ecommerce\Tracker\EcommerceRequestProcessor::manipulateRequest()...
    1638957566: Executing Piwik\Plugins\SitesManager\Tracker\SitesManagerRequestProcessor::manipulateRequest()...
    1638957566: Executing Piwik\Plugins\PrivacyManager\Tracker\RequestProcessor::manipulateRequest()...
    1638957566: Executing Piwik\Plugins\Heartbeat\Tracker\PingRequestProcessor::manipulateRequest()...
    1638957566: Executing Piwik\Plugins\PagePerformance\Tracker\PerformanceDataProcessor::manipulateRequest()...
    1638957566: Executing Piwik\Plugins\CustomDimensions\Tracker\CustomDimensionsRequestProcessor::manipulateRequest()...
    1638957566: Executing Piwik\Plugins\CoreHome\Tracker\VisitRequestProcessor::processRequestParams()...
    1638957567: Search bot detected, visit excluded
    1638957567: Visit is already excluded, no need to check DoNotTrack support.
    1638957567: Visitor excluded.
    1638957567: -> aborting due to processRequestParams method
    1638957567: -> Scheduled tasks not running in Tracker: Browser archiving is disabled.
    1638957567: Nothing to notice => default behaviour
    1638957567: End of the page.
    1638957567: array (
    )
    
    Thread Starter Alexandre Froger

    (@frogerme)

    A way to fix the Tag Manager for WooCommerce and avoiding the hit being tracked as bot hit:

    
    <?php
    /*
    Plugin Name: Fix Matomo Tag Manager
    Plugin URI: https://anyape.com/
    Description: Fix Matomo Tag Manager
    Version: 1.0
    Author: Alexandre Froger
    Author URI: https://froger.me/
    */
    
    if ( ! defined( 'ABSPATH' ) ) {
    	exit; // Exit if accessed directly
    }
    
    class FixMatomoTagManager {
    
    	public function __construct() {
    		add_filter( 'http_headers_useragent', array( $this, 'http_headers_useragent' ), 10, 2 );
    	}
    
    	public function http_headers_useragent( $user_agent, $url ) {
    
    		if ( false !== strpos( $url, 'matomo.php' ) || false !== strpos( $url, 'matomo/v' ) ) {
    			$user_agent = 'MatomoAjaxTrackerForWP; ' . get_bloginfo( 'url' );
    		}
    
    		return $user_agent;
    	}
    }
    
    add_action( 'plugins_loaded', 'fix_matomo_tag_manager', 0, 0 );
    function fix_matomo_tag_manager() {
    	// Always filter classes adding hooks to allow 3rd party to deregister hooks or override the object
    	$fix_matomo_tag_manager = apply_filters( 'fix_matomo_tag_manager', new FixMatomoTagManager() );
    }
    
    

    That’s a quick untested scaffold taken out of tested and working code from a larger project.
    Better would be to add this filter hook in the core plugin itself before using MatomoTracker

    Plugin Author Thomas

    (@tsteur)

    @frogerme I’ve had another look and when you select “Tag Manager” in the “Add tracking code” section in “WP Admin Dashboard -> Matomo Analytics -> Settings”, then it does let you select a User ID in the settings further below. Does this work maybe? You wouldn’t need to do anything in the Tag Manager for the user ID when selecting the setting.

    I fully agree this should be possible easily to track a user ID. If this doesn’t work for you, we can investigate and also think about pushing the UserID to the data layer automatically.

    Hi @frogerme

    does it sound good for you?

    Kind regards

    Mat

    Hi @frogerme

    Without any answer I close this topic.
    If you need further assistance feel free to open a new topic.
    Kind regards

    Mat

    closed

Viewing 8 replies - 1 through 8 (of 8 total)
  • The topic ‘Missing User ID when using Tag Manager’ is closed to new replies.