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

- Type: PHP
- Runs: Run everywhere
- Category: [Search](https://wpide.com/library/category/search/)
- Tags: search, statistics, dashboard
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/log-site-searches/

## Code

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

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Log Site Searches in a Dashboard Widget" 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/
