Track Searches With No Results in GA4
Sends a search_no_results event with the search term to Google Analytics 4 when a site search finds nothing, showing you what visitors want but cannot find.
Opens WPIDE on
Code
add_action( 'wp_footer', function () {
global $wp_query;
if ( ! is_search() || $wp_query->found_posts > 0 ) {
return;
}
?>
<script>
if (typeof gtag === 'function') {
gtag('event', 'search_no_results', { search_term: <?php echo wp_json_encode( mb_substr( get_search_query( false ), 0, 100 ) ); ?> });
}
</script>
<?php
} );
Notes
Needs the GA4 tag on the page. Register search_term as an event-scoped custom dimension to report on terms.
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.