search blog posts by author first name and or last name

The question:

I am trying to create and endpoint where blog posts can be searched by author first name and/or last name. I was trying to do this with WP_Query but it uses the user nice name for the search which is not working. Is there a way to do this using a built in query or do I need to do a custom SQL query?

add_action( 'rest_api_init', function () {
  register_rest_route( 'blog-posts/v1', 'blog-by-author', array(
    'methods' => 'POST',
    'callback' => 'get_posts_by_author',
    'permission_callback' => '__return_true',
  ) );
} );

function get_posts_by_author(WP_REST_Request $request) {
    $data = $request->get_params();
    $author_name = $data['author_name'];
   // this uses nice name, not first/last name
    $query = new WP_Query( array( 'author_name' => $author_name ) );
    return print_r($query);

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

Actually, when you set author_name, WP_Query will use get_user_by( 'slug', <author name> ) to find a user with the specified “nice name” (user_nicename) value, and if found, then WP_Query sets the author arg to the found user’s ID.

Therefore you can follow the same approach, but you would use get_users() to find users having the specified first and/or last name and use the author (or author__in) arg with WP_Query. E.g.

$users = get_users( array(
    'meta_query'  => array(
        'relation' => 'OR',
            'key'     => 'first_name',
            'value'   => $request['author_name'],
            'compare' => 'LIKE',
            'key'     => 'last_name',
            'value'   => $request['author_name'],
            'compare' => 'LIKE',
    'fields'      => 'ID',
) );

if ( ! empty( $users ) ) {
    $query = new WP_Query( array( 'author' => $users[0] ) );
    // or to include all found users..
//  $query = new WP_Query( array( 'author__in' => $users ) );

    // ... your code.

Additional Notes

  • You don’t have to do the $data = $request->get_params(); because you could just access parameters via direct array access on the WP_REST_Request object, e.g. $request['author_name'] like in my example above.

  • You should register author_name using args in the third parameter for register_rest_route(), or at least, check that it’s not empty before calling get_users().

  • I know the print_r() in your code is just for testing, but the function will actually echo the output unless if the second parameter is set to true..

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment