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