WordPress Search for Author

How to Include Author Name in WordPress Search Result

By default WordPress search doesn’t work for author name. It only searches through content. So if you write author name inside your post, 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 author name in WordPress Search.

  • With Plugin
  • Without Plugin

I prefer without plugin solution. 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 Ivory Search plugin. This is a great free plugin. Install it and activate.

Click on Edit for Default Search Form.

ivory search plugin

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

Author Name in Ivory Search

Click on “Save Form”. Done!

2. Without Plugin

In your theme’s functions.php file, paste 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.

Spread the love

A teacher by profession, a traveler by passion and a netizen by choice.

Morshed Alam

You use WordPress! Why don't we share our experience! It may be a tutorial, tips, tricks or about security, performance or WordPress news. Write Today

2 thoughts on “How to Include Author Name in WordPress Search Result”

Leave a Comment

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