# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Multisite](https://wpide.com/library/category/multisite/)
- Tags: network-settings, analytics, ga4
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/ms-network-tracking-code/

## Code

```php
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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "One Analytics Tag for Every Site on the Network" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
