3

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'

2

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();

8
  • 1
    He is not using the init action hook, it is using wp_loaded. The init in his code is a class method.
    – cybmeta
    Sep 11 '14 at 9:10
  • Still, wp_loaded is too early. Sep 11 '14 at 9:11
  • You're right about wp_loaded being too early but hooking to wp doesn't solve the issue. The debug notice remains Sep 11 '14 at 9:15
  • I've updated my question Sep 11 '14 at 9:19
  • I've tested your code in init, wp_loaded and wp action hooks and it works perfectly in wp action hook and it doesn't work in the other hooks as suggested by @TheDeadMedic. Your problem totally different. You see a PHP error message that says what the error is and the exact line where the error occurs, so you have what, why and where in the error message. That's why PHP error messages, in general, are off topic in this site.
    – cybmeta
    Sep 11 '14 at 9:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.