One Analytics Tag for Every Site on the Network
Adds a Google Analytics 4 measurement ID field to Network Admin > Settings and prints the tag on every site, so new sites are tracked automatically.
Opens WPIDE on
Code
if ( ! is_multisite() ) {
return;
}
add_action( 'wpmu_options', function () {
?>
<h2><?php esc_html_e( 'Network analytics' ); ?></h2>
<table class="form-table" role="presentation">
<tr>
<th scope="row"><label for="wpide_network_ga4"><?php esc_html_e( 'GA4 measurement ID' ); ?></label></th>
<td><input type="text" name="wpide_network_ga4" id="wpide_network_ga4" class="regular-text" placeholder="G-XXXXXXXXXX" value="<?php echo esc_attr( get_site_option( 'wpide_network_ga4', '' ) ); ?>"></td>
</tr>
</table>
<?php
} );
add_action( 'update_wpmu_options', function () {
if ( isset( $_POST['wpide_network_ga4'] ) && current_user_can( 'manage_network_options' ) ) {
$id = strtoupper( sanitize_text_field( wp_unslash( $_POST['wpide_network_ga4'] ) ) );
update_site_option( 'wpide_network_ga4', preg_match( '/^G-[A-Z0-9]+$/', $id ) ? $id : '' );
}
} );
add_action( 'wp_head', function () {
$id = get_site_option( 'wpide_network_ga4', '' );
if ( ! $id || current_user_can( 'edit_posts' ) || is_preview() ) {
return;
}
?>
<script async src="https://www.googletagmanager.com/gtag/js?id=<?php echo esc_attr( $id ); ?>"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', <?php echo wp_json_encode( $id ); ?>, { site_id: <?php echo (int) get_current_blog_id(); ?> });
</script>
<?php
}, 5 );
Notes
Logged-in users who can edit posts are not tracked. Leave the field empty to switch tracking off.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.