• Amelia

    Member
    4 June 2023 at 7:41 am

    To dynamically change the userId with the actual user Id in the dataLayer, you need to use a PHP function to fetch the user ID and then echo it within the JavaScript snippet. Also, keep in mind that the user ID is usually stored as part of user authentication in a session variable or a cookie in PHP.

    Hence, assuming you authenticate users with something like WordPress, the code would look something like this:

    `
    window.dataLayer = window.dataLayer || [];
    window.dataLayer.push({
    ‘event’ : ‘login’,
    ‘userId’: ”
    });
    `
    Here, get_current_user_id(); is a WordPress function to get the currently logged in user’s ID. Also remember this code must be executed after the user logs in, potentially you might want to check if the user is already logged in before pushing the data to the dataLayer.

    However, if you’re not using WordPress or any other CMS with a built-in function to get the user ID, you would need to fetch it from the session variable or cookie where the user information is stored. For instance, it might look something like $_SESSION['userId']. It’s also worth noting that the specifics of how you fetch the userID and where you put this script might vary considerably depending on your website’s specifics.