Skip to content

Instantly share code, notes, and snippets.

@chavesm
Last active February 5, 2021 10:25
Show Gist options
  • Save chavesm/b35558f51bafd608045db090b97d5893 to your computer and use it in GitHub Desktop.
Save chavesm/b35558f51bafd608045db090b97d5893 to your computer and use it in GitHub Desktop.
Set a Google Analytics Custom Dimension using a MonsterInsights PHP Filter
<?php
/**
* This example sets custom dimension #9 to be the WordPress
* post ID of the page/post being visited.
*
* - Change the number 9 to your custom dimension index number.
* - Change the call to get_the_id() to what you need the CD value to be.
*/
add_filter(
'monsterinsights_frontend_tracking_options_analytics_before_pageview',
function( $options ) {
$options[ 'dimension9' ] = "'set', 'dimension9', '" . get_the_id() . "'";
return $options;
},
20 // priority
);
<?php
/**
* Helper function for retrieving WordPress user metadata
* if needed to use as a custom dimension. Remember to
* respect PII here. Any Google PII violations can result
* in account suspensions. E.g., the user role wouldn't
* be a PII concern, but the email address would be.
*
* Another use case is to use the user ID to retrieve
* custom meta such as a membership
* level.
*/
// Example getter for the WP internal user ID.
function 1004596_get_user_id() {
$current_user = wp_get_current_user();
if ( ! ( $current_user instanceof WP_User ) ) {
return;
}
$user_ID = $current_user->ID;
return $user_ID;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment