How to get author ID when an author page is being viewed?

I’m having problems getting the author ID in my plugin’s init() method.

I’ve hooked init() to wp:

public function __construct() {
    add_action( 'wp', array( $this, 'init' ) );
}

My init() method:

public function init() {
    // Get the author ID if the author page is being viewed.
    if ( is_author() ) {
        $author = ( get_query_var( 'author_name' ) ) ? get_user_by( 'slug', get_query_var( 'author_name' ) ) : get_userdata( get_query_var( 'author' ) );
    }
    // I want to be able to do $author->ID here but I get a debug notice.
}

I’m getting the debug notice “Trying to get property of non-object”. I suspect this is because the following statement hasn’t worked:

$author = ( get_query_var( 'author_name' ) ) ? get_user_by( 'slug', get_query_var( 'author_name' ) ) : get_userdata( get_query_var( 'author' ) );

Inside init(), how can I get the author ID when an author page is being viewed?

Update: As pointed out by TheDeadMedic, I should be hooking to wp instead of plugins_loaded. That doesn’t solve the problem though. $author remains a ‘non-object’

1 Answer
1

wp_loaded is too early, the request hasn’t been parsed yet – use the action wp instead (called at the end of WP::main(), once the request has been parsed and posts have been queried).

To get the user object, just use $author = get_queried_object();

Leave a Comment