WordPress Search for Author

How to Include Author Name in WordPress Search Result

By default, WordPress search doesn’t work for author names. It only searches through content. So if you write the author’s name inside your post, the search result will pull out that post. Otherwise, if you search for that author, you will get “No results found.”

Today I will show you two solutions to include the author name in WordPress search.

  • With Plugin
  • Without Plugin

I prefer a solution without a plugin. Because I don’t like to add a plugin with lots of files and code if it can be done with some lines of code. Let’s see the plugin solution first.

1. With Plugin

Today, our hero is the Ivory Search plugin. This is a great free plugin. Install it and activate it.

Click on Edit for Default Search Form.

Ivory Search

From “Extras,” you will find the Author section. Enable the “Search author Display Name and display the posts created by that author” option.

Include author in search

Click on “Save Form.” Done!

2. Without Plugin

In your theme’s functions.php file, paste the following code:

add_filter( 'posts_search', 'db_filter_authors_search' );
function db_filter_authors_search( $posts_search ) {
    if ( !is_search() || empty( $posts_search ) )
        return $posts_search;
    global $wpdb;
    add_filter( 'pre_user_query', 'db_filter_user_query' );
    $search = sanitize_text_field( get_query_var( 's' ) );
    $args = array(
        'count_total' => false,
        'search' => sprintf( '*%s*', $search ),
        'search_fields' => array('display_name','user_login',),
        'fields' => 'ID',
    );
    $matching_users = get_users( $args );
    remove_filter( 'pre_user_query', 'db_filter_user_query' );
    if ( empty( $matching_users ) )
        return $posts_search;
    $posts_search = str_replace( ')))', ")) OR ( {$wpdb->posts}.post_author IN (" . implode( ',', array_map( 'absint', $matching_users ) ) . ")))", $posts_search );
    return $posts_search;
}
function db_filter_user_query( &$user_query ) {
    if ( is_object( $user_query ) )
        $user_query->query_where = str_replace( "user_nicename LIKE", "display_name LIKE", $user_query->query_where );
    return $user_query;
}

Let me know if it works or not.

1 thought on “How to Include Author Name in WordPress Search Result”

Leave a Comment

Your email address will not be published. Required fields are marked *