# Track 404 Errors in GA4

> Sends a page_not_found event to Google Analytics 4 with the broken URL and the page the visitor came from, so you can find and fix dead links.

- Type: PHP
- Runs: Frontend only
- Category: [Analytics & Tracking](https://wpide.com/library/category/analytics/)
- Tags: google-analytics, ga4, 404, seo
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/analytics-ga4-404-event/

## Code

```php
add_action( 'wp_footer', function () {
    if ( ! is_404() ) {
        return;
    }
    ?>
<script>
if (typeof gtag === 'function') {
    gtag('event', 'page_not_found', { page_location: location.href, page_referrer: document.referrer || '(direct)' });
}
</script>
    <?php
} );
```

## Notes

Needs the GA4 tag on the page. Find the events under Reports > Engagement > Events.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Track 404 Errors in GA4" 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/
