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.
Opens WPIDE on
Code
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 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.