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);
}
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
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',
array(
'key' => 'first_name',
'value' => $request['author_name'],
'compare' => 'LIKE',
),
array(
'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 theWP_REST_Requestobject, e.g.$request['author_name']like in my example above. -
You should register
author_nameusingargsin the third parameter forregister_rest_route(), or at least, check that it’s not empty before callingget_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 totrue..
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0