Using WordPress ‘get_author_name()’ PHP function

The get_author_name() WordPress PHP function retrieves the preferred display name of a specified author.

Usage

To use the get_author_name() function, you simply need to pass the author’s ID as an argument. If the function call is successful, it will return the author’s display name.

$author_name = get_author_name(1); // Assuming 1 is the ID of the author
echo $author_name; // Outputs the display name of the author with ID 1

Parameters

  • $auth_id (int, optional): The ID of the author. Default value is false, which returns the current author’s name.

More Information

See WordPress Developer Resources: get_author_name()

This function was introduced in WordPress 1.5.1. It is not deprecated and is generally used to retrieve author information for posts. The source code can be found in wp-includes/author-template.php.

Related functions include get_the_author_meta(), which retrieves the metadata of an author.

Examples

Retrieving the Name of the Current Post’s Author

This example retrieves the name of the author of the current post.

$author_name = get_author_name();
echo "Post written by " . $author_name;

Displaying the Name of a Specific Author

Here, we are retrieving the display name of the author with an ID of 5.

$author_name = get_author_name(5);
echo "Author: " . $author_name;

Checking if Author Exists

In this case, we are checking if an author exists before retrieving the name.

$author_id = 7;
if (get_userdata($author_id)) {
    $author_name = get_author_name($author_id);
    echo "Author: " . $author_name;
} else {
    echo "No author found with ID: " . $author_id;
}

Using in a Loop

We can use the function in a loop to display the names of all authors of posts in a query.

$query = new WP_Query(array('posts_per_page' => -1));

if($query->have_posts()) : 
    while($query->have_posts()) : 
        $query->the_post();
        $author_name = get_author_name();
        echo "Post: " . get_the_title() . ", Author: " . $author_name . "<br>";
    endwhile;
endif;

Displaying in a Template

Lastly, let’s display the author name in a WordPress template.

echo "Written by " . get_author_name(get_the_author_meta('ID'));

Here, the get_the_author_meta(‘ID’) function retrieves the ID of the current post’s author, which is then passed to the get_author_name() function.