Out of the box, WordPress’ search isn’t that great. It only returns posts based on a LIKE query against the post title or post content. Often, you’ll want it to match against other data associated with your post, possibly including the author, tags, post meta fields, etc. These queries can get complex to perform on the fly, however.
The following code snippet allows you to include posts by matching authors in your search results. We’re modifying any search queries to also include all posts whose author display name or user login matches the query. You can change this to be the author’s first name, last name, or other fields.
/**
* Include posts from authors in the search results where
* either their display name or user login matches the query string
*
* @author danielbachhuber
*/
add_filter( 'posts_search', 'db_filter_authors_search' );
function db_filter_authors_search( $posts_search ) {
// Don't modify the query at all if we're not on the search template
// or if the LIKE is empty
if ( !is_search() || empty( $posts_search ) )
return $posts_search;
global $wpdb;
// Get all of the users of the blog and see if the search query matches either
// the display name or the user login
$all_users = get_users();
$matching_users = array();
foreach( $all_users as $blog_user ) {
if ( false !== stripos( $blog_user->display_name, get_query_var('s') ) || false !== stripos( $blog_user->user_login, get_query_var('s') ) )
$matching_users[] = $blog_user->ID;
}
// Don't modify the query if there aren't any matching users
if ( empty( $matching_users ) )
return $posts_search;
// Take a slightly different approach than core where we want all of the posts from these authors
$posts_search = rtrim( $posts_search, ') ' );
$posts_search .= ")) OR ( {$wpdb->posts}.post_author IN (" . implode( ',', array_map( 'absint', $matching_users ) ) . ")";
return $posts_search . '))';
}