Halloween Sale 15% off Ends in See the plans
PHP

Search Posts by Author Name

Makes the site search also return posts written by authors whose name matches the search, so "maria" finds everything by Maria Lopez.

Don’t have WPIDE yet? Install it on your site

Code

add_filter( 'posts_search', function ( $search, $query ) {
    global $wpdb;

    if ( '' === $search || is_admin() || ! $query->is_main_query() || ! $query->is_search() ) {
        return $search;
    }

    $phrase = trim( (string) $query->get( 's' ) );

    if ( strlen( $phrase ) < 3 ) {
        return $search;
    }

    // Authors whose display name contains the search, for example "maria" finds posts by Maria Lopez.
    $authors = get_users( array(
        'search'              => '*' . $phrase . '*',
        'search_columns'      => array( 'display_name' ),
        'has_published_posts' => true,
        'number'              => 20,
        'fields'              => 'ID',
    ) );

    if ( ! $authors ) {
        return $search;
    }

    $password = '';
    $marker   = " AND ({$wpdb->posts}.post_password = '') ";

    if ( substr( $search, -strlen( $marker ) ) === $marker ) {
        $password = $marker;
        $search   = substr( $search, 0, -strlen( $marker ) );
    }

    $inner = preg_replace( '/^\s*AND\s*/', '', $search );
    $ids   = implode( ',', array_map( 'absint', $authors ) );

    return " AND ( {$wpdb->posts}.post_author IN ({$ids}) OR {$inner} ){$password}";
}, 10, 2 );

Notes

Matches display names of users who have published posts, for searches of three characters or more.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.