Created
March 15, 2019 15:39
-
-
Save jaygidwitz/a0d1dd6eacec304bdcab1940a1e3e1d9 to your computer and use it in GitHub Desktop.
logged in user role custom dimension
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Plugin Name: MonsterInsights User Role Dimension | |
* Description: Add a user role to the dimensions options in MonsterInsights. | |
* Version: 1.0.0 | |
* Author: MonsterInsights Support Team | |
* Author URI: https://www.monsterinsights.com | |
*/ | |
function monsterinsights_add_user_role_to_dimensions( $dimensions ) { | |
$dimensions['user_role'] = array( | |
'title' => __( 'User Role', 'monsterinsights-ctd' ), | |
'label' => __( 'Most popular user roles', 'monsterinsights-ctd' ), | |
'enabled' => true, | |
'metric' => 'pageviews', | |
); | |
return $dimensions; | |
} | |
add_filter( 'monsterinsights_available_custom_dimensions', 'monsterinsights_add_user_role_to_dimensions' ); | |
function monsterinsights_user_role_tracking( $options ) { | |
$dimensions = monsterinsights_get_option( 'custom_dimensions', array() ); | |
if ( ! empty( $dimensions ) && is_array( $dimensions ) ) { | |
// Sort by array key `id` value. | |
$id = array(); | |
foreach ( $dimensions as $key => $row ) { | |
if ( empty( $row['type'] ) || empty( $row['id'] ) ) { | |
unset( $dimensions[ $key ] ); | |
continue; | |
} | |
$id[ $key ] = $row['id']; | |
} | |
array_multisort( $id, SORT_ASC, $dimensions ); | |
foreach ( $dimensions as $dimension ) { | |
if ( empty( $dimension['type'] ) || empty( $dimension['id'] ) ) { | |
continue; | |
} | |
$type = $dimension['type']; | |
$id = $dimension['id']; | |
$value = ''; | |
switch ( $type ) { | |
case 'user_role': | |
$value = monsterinsights_user_role_get_dimension(); | |
break; | |
default: | |
// don't do anything. | |
break; | |
} | |
if ( ! empty( $value ) ) { | |
$options[ 'dimension' . $id ] = monsterinsights_user_role_get_dimension_output( $id, $value ); | |
} | |
} | |
} | |
return $options; | |
} | |
add_filter( 'monsterinsights_frontend_tracking_options_analytics_before_pageview', 'monsterinsights_user_role_tracking' ); | |
/** | |
* @param $id | |
* @param $value | |
* | |
* @return string | |
*/ | |
function monsterinsights_user_role_get_dimension_output( $id, $value ) { | |
return "'set', 'dimension" . absint( $id ) . "', '" . esc_js( addslashes( $value ) ) . "'"; | |
} | |
/** | |
* @return string | |
*/ | |
function monsterinsights_user_role_get_dimension() { | |
$value = ''; | |
if ( is_user_logged_in() ) { | |
$user = wp_get_current_user(); | |
if ( ! empty( $user->roles ) ) { | |
$value = implode( ',', $user->roles ); | |
} | |
} | |
return $value; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment