Home » Tutorial » How to Include Author Name in WordPress Search Result

How to Include Author Name in WordPress Search Result

WordPress Search for Author

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

From “Extras“, you will find Author section. Enable “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 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.

Read more from Tutorial

Written by:

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

Have you written on ThoughtMight?Write Today



Leave a Comment

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