Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Add a new "Membership Level" dimension to track via MonsterInsights.
<?php
/**
* Add a new "Membership Level" Custom Dimension to your Google Analytics tracking code.
*
* Requires Paid Memberships Pro, MonsterInsights Pro and the MonsterInsights - Dimensions Addon.
*/
/**
* Filter for adding the new dimension as under Insights > Settings > Dimensions
*/
function my_pmpro_membership_level_custom_dimension( $custom_dimensions ) {
if( defined( 'PMPRO_VERSION' ) ) {
$my_custom_dimensions = array(
'membership_level' => array(
'title' => __( 'Membership Level', 'paid-memberships-pro' ),
'label' => __( 'The membership level of the user', 'paid-memberships-pro' ),
'enabled' => true,
'metric' => 'sessions',
),
);
$custom_dimensions = array_merge( $custom_dimensions, $my_custom_dimensions );
}
return $custom_dimensions;
}
add_filter( 'monsterinsights_available_custom_dimensions', 'my_pmpro_membership_level_custom_dimension' );
/**
* Filter for adding the tracking code for the "Membership Level" Custom Dimension.
*/
function my_pmpro_monsterinsights_frontend_tracking_options_analytics_before_pageview( $options ) {
if ( defined( 'PMPRO_VERSION' ) ) {
// Get all active Custom Dimensions in MonsterInsights.
$dimensions = monsterinsights_get_option( 'custom_dimensions', array() );
if ( ! empty( $dimensions ) && is_array( $dimensions ) ) {
foreach ( $dimensions as $dimension ) {
// Set the tracking value for membership_level Custom Dimension in MonsterInsights.
if ( ( $dimension['type'] === 'membership_level' ) && ! empty( $dimension['id'] ) ) {
$type = $dimension['type'];
$id = $dimension['id'];
if ( is_user_logged_in() ) {
// Get the current users's membership level ID.
$current_user_membership_level = pmpro_getMembershipLevelForUser( get_current_user_id() );
$value = $current_user_membership_level->ID;
} else {
// Set the tracked membership level ID to no_level.
$value = 'no_level';
}
// Set the Custom Dimension's value to the output.
if ( ! empty( $value ) ) {
$options[ 'dimension' . $id ] = "'set', 'dimension" . absint( $id ) . "', '" . esc_js( addslashes( $value ) ) . "'";
}
}
}
}
}
return $options;
}
add_filter( 'monsterinsights_frontend_tracking_options_analytics_before_pageview', 'my_pmpro_monsterinsights_frontend_tracking_options_analytics_before_pageview' );
@laurenhagan0306

This comment has been minimized.

Copy link

@laurenhagan0306 laurenhagan0306 commented Apr 8, 2021

This recipe is included in the blog post on "Putting Google Analytics to work for your Membership Site" at Paid Memberships Pro here: https://www.paidmembershipspro.com/putting-google-analytics-to-work-for-your-membership-site/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment