# Search Posts by Author Name

> Makes the site search also return posts written by authors whose name matches the search, so "maria" finds everything by Maria Lopez.

- Type: PHP
- Runs: Run everywhere
- Category: [Search](https://wpide.com/library/category/search/)
- Tags: search, authors, relevance
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/search-matches-author-names/

## Code

```php
add_filter( 'posts_search', function ( $search, $query ) {
    global $wpdb;

    if ( '' === $search || is_admin() || ! $query->is_main_query() || ! $query->is_search() ) {
        return $search;
    }

    $phrase = trim( (string) $query->get( 's' ) );

    if ( strlen( $phrase ) < 3 ) {
        return $search;
    }

    // Authors whose display name contains the search, for example "maria" finds posts by Maria Lopez.
    $authors = get_users( array(
        'search'              => '*' . $phrase . '*',
        'search_columns'      => array( 'display_name' ),
        'has_published_posts' => true,
        'number'              => 20,
        'fields'              => 'ID',
    ) );

    if ( ! $authors ) {
        return $search;
    }

    $password = '';
    $marker   = " AND ({$wpdb->posts}.post_password = '') ";

    if ( substr( $search, -strlen( $marker ) ) === $marker ) {
        $password = $marker;
        $search   = substr( $search, 0, -strlen( $marker ) );
    }

    $inner = preg_replace( '/^\s*AND\s*/', '', $search );
    $ids   = implode( ',', array_map( 'absint', $authors ) );

    return " AND ( {$wpdb->posts}.post_author IN ({$ids}) OR {$inner} ){$password}";
}, 10, 2 );
```

## Notes

Matches display names of users who have published posts, for searches of three characters or more.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Search Posts by Author Name" 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/
