Created
February 7, 2012 16:47
-
-
Save danielbachhuber/1760666 to your computer and use it in GitHub Desktop.
Include author matches in search results
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /** | |
| * 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, $wp_query; | |
| // 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, $wp_query->query_vars['s'] ) || false !== stripos( $blog_user->user_login, $wp_query->query_vars['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 . '))'; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment