Last active
May 15, 2023 15:53
-
-
Save rdhimanam/8920abb244cd1468fa968470d7023709 to your computer and use it in GitHub Desktop.
Add custom dimensions to admin list and frontend values
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
/** | |
* This would add custom dimension to the admin list inside settings. | |
*/ | |
function monsterinsights_add_dimensions_to_admin_list( $dimensions ) { | |
// Add dimension to array with a unique key 'services' | |
$dimensions['services'] = array( | |
'title' => __( 'Services', 'monsterinsights-dimensions' ), // Label | |
'label' => __( 'Services', 'monsterinsights-dimensions' ), // Description | |
'enabled' => true, | |
'metric' => 'sessions', | |
); | |
$dimensions['project'] = array( | |
'title' => __( 'Project', 'monsterinsights-dimensions' ), | |
'label' => __( 'Project', 'monsterinsights-dimensions' ), | |
'enabled' => true, | |
'metric' => 'sessions', | |
); | |
return $dimensions; | |
} | |
add_filter('monsterinsights_available_custom_dimensions', 'monsterinsights_add_dimensions_to_admin_list'); | |
/** | |
* This would add the value of custom dimensions added above. | |
*/ | |
function monsterinsights_custom_add_dimensions_value( $options ) { | |
$post_type = ''; | |
if ( is_singular() ) { | |
$post_type = get_post_type( get_the_ID() ); | |
} | |
if ( '' === $post_type ) { | |
return; | |
} | |
$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 'services': | |
$value = $post_type; //Get whatever value we need to send in the dimension; | |
break; | |
case 'project': | |
$value = $post_type; //Get whatever value we need to send in the dimension; | |
break; | |
} | |
if ( ! empty( $value ) ) { | |
$options[ 'dimension' . $id ] = "'set', 'dimension" . absint( $id ) . "', '" . esc_js( addslashes( $value ) ) . "'"; | |
} | |
} | |
} | |
return $options; | |
} | |
add_filter( 'monsterinsights_frontend_tracking_options_persistent_gtag_before_pageview', 'monsterinsights_custom_add_dimensions_value', 20 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment