Log Site Searches in a Dashboard Widget
Records what visitors search for, how often, and whether anything was found, and shows the top searches in a dashboard widget so you can spot missing content.
Opens WPIDE on
Code
add_action( 'template_redirect', function () {
global $wp_query;
if ( ! is_search() || is_paged() || current_user_can( 'edit_posts' ) ) {
return;
}
$term = strtolower( trim( (string) get_search_query( false ) ) );
if ( '' === $term || strlen( $term ) > 100 ) {
return;
}
$log = get_option( 'wpide_search_log', array() );
$log = is_array( $log ) ? $log : array();
if ( ! isset( $log[ $term ] ) ) {
$log[ $term ] = array( 'count' => 0, 'results' => 0, 'last' => 0 );
}
$log[ $term ]['count']++;
$log[ $term ]['results'] = (int) $wp_query->found_posts;
$log[ $term ]['last'] = time();
if ( count( $log ) > 300 ) {
uasort( $log, function ( $a, $b ) {
return $b['last'] <=> $a['last'];
} );
$log = array_slice( $log, 0, 300, true );
}
update_option( 'wpide_search_log', $log, false );
} );
add_action( 'wp_dashboard_setup', function () {
if ( ! current_user_can( 'manage_options' ) ) {
return;
}
wp_add_dashboard_widget( 'wpide_search_log', 'Top Site Searches', function () {
$log = get_option( 'wpide_search_log', array() );
if ( ! is_array( $log ) || ! $log ) {
echo '<p>No searches recorded yet.</p>';
return;
}
uasort( $log, function ( $a, $b ) {
return $b['count'] <=> $a['count'];
} );
echo '<table class="widefat striped"><thead><tr><th>Search</th><th>Times</th><th>Results</th></tr></thead><tbody>';
foreach ( array_slice( $log, 0, 15, true ) as $term => $row ) {
$results = (int) $row['results'];
echo '<tr><td>' . esc_html( $term ) . '</td><td>' . esc_html( number_format_i18n( (int) $row['count'] ) ) . '</td><td' . ( 0 === $results ? ' style="color:#d63638;font-weight:600;"' : '' ) . '>' . esc_html( number_format_i18n( $results ) ) . '</td></tr>';
}
echo '</tbody></table>';
} );
} );
Notes
Searches by logged-in editors are not counted. The log keeps the 300 most recent distinct terms in one option.
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.