Search code examples
phpwordpressmetaauthormultisite

How to load User Meta?


Wordpress author.php is not loading the correct information from user meta. It's loading whoever is currently logged in to the blog and not displaying the person who it links to for example:

http://www.website.com/author/username1
http://www.website.com/author/username2

is displaying the same despite been two different users. I've done what is asked, however I'm still confused to why its only loading the currently user meta and not the meta of the username?

This is my author template:

<?php get_header(); ?>  

<div class="author-name">
<?php echo get_the_author_meta('first_name'); ?>
<?php echo get_the_author_meta('last_name'); ?> 
<?php echo get_user_role('user_role'); ?>
</div>

<div class="author-information">
Username: <?php echo get_the_author('user_nicename'); ?>
</div>

<?php get_footer(); ?>  

Solution

  • You must supply the User ID when using get_the_author_meta() to get a different user than the one in the loop or currently logged in.

    Assuming username1 and username2 are actual usernames in the users database table you can get the username from the URL by using the following snippet:

    $username_from_url = basename( get_permalink() );
    

    And then:

    $user = get_user_by( 'login', $username_from_url );
    

    Now you have the full $user object with ID and everything.

    Edit: complete solution

    User visits an URL with the following pattern /page/somename where somename corresponds to the user´s user_nicename in the database table users.

    <?php
        $username_from_url = basename( get_permalink() );
        $user = get_user_by( 'slug', $username_from_url );
    
        echo get_the_author_meta( 'first_name', $user->ID );
        echo get_the_author_meta( 'last_name', $user->ID );
    
        foreach ($user->roles as $role) {
            // You can also use get_role( $role ) to get more data on the role
            echo $role;
        }
    
        echo __( "Username:" ) . " " . $user->user_nicename;
    ?>