Search posts by post author name

I want to search posts publish by particular author. For this purpose I added a filter in functions.php:

function wpse_29570_where_filter($where){
        global $wpdb;
        if( is_search() ) {
            $search= get_query_var('s');
            $query=$wpdb->prepare("SELECT $wpdb->users.ID  FROM $wpdb->users WHERE  $wpdb->users.display_name LIKE '%%%s%%' ", $search );
            $authorID= $wpdb->get_var( $query );//die;

            if($authorID){
                $where = "  AND  ( atl_posts.post_author = {$authorID} ) ";
            }
            //echo $where;
         }
         return $where;
    }

    add_filter('posts_where','wpse_29570_where_filter');

It I echo the where condition it gives

Read More
AND ( atl_posts.post_author = 1 ) 

but when I search by typing admin it shows a blank result.

Please help me to make it work.
Can anyone tell me a better way to do it?

Related posts

Leave a Reply

1 comment

  1. This line is likely the issue –

    $where = "  AND  ( atl_posts.post_author = {$authorID} ) ";
    

    You are replacing the contents of $where, not changing it. You have to use . before =

    $where.= "  AND  ( atl_posts.post_author = {$authorID} ) ";