Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bhubbard/6734c1458965daae8381f9f9f7a4ab8e to your computer and use it in GitHub Desktop.
Save bhubbard/6734c1458965daae8381f9f9f7a4ab8e to your computer and use it in GitHub Desktop.
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' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment