star
star

Reputation: 174

WordPress list authors search by first or second name

The idea is to make a search page for listing authors of website ( a blog or something like that) and the keyword for search will be first name or last name of author.

As far as I have looked around there isn't any WordPress function which allow to query authors based on first and last name.

Upvotes: 0

Views: 417

Answers (1)

Jared
Jared

Reputation: 12524

You need to use the meta_query parameter of WP_User_Query

The codex has an example of searching first and last name here: https://codex.wordpress.org/Class_Reference/WP_User_Query#Examples

Relevant Code:

// The search term
$search_term = 'Ross';

// WP_User_Query arguments
$args = array (
    'order' => 'ASC',
    'orderby' => 'display_name',
    'meta_query' => array(
        'relation' => 'OR',
        array(
            'key'     => 'first_name',
            'value'   => $search_term,
            'compare' => 'LIKE'
        ),
        array(
            'key'     => 'last_name',
            'value'   => $search_term,
            'compare' => 'LIKE'
        ),
    )
);

// Create the WP_User_Query object
$wp_user_query = new WP_User_Query($args);

// Get the results
$authors = $wp_user_query->get_results();

// Check for results
if (!empty($authors)) {
    echo '<ul>';
    // loop trough each author
    foreach ($authors as $author)
    {
        // get all the user's data
        $author_info = get_userdata($author->ID);
        echo '<li>'.$author_info->first_name.' '.$author_info->last_name.'</li>';
    }
    echo '</ul>';
} else {
    echo 'No authors found';
}

Upvotes: 2

Related Questions