If logged in user views his profile page

I did some search but could not find the exact answer.

My goal is the display "edit link" on profile pages but it will only visible to that user.

For example, John logged in and views the page site.com/author/john, then he will see edit link but he will not see this link on other users page.

If I use the code below, logged in user sees the link on every profile page.

<?php if ( is_user_logged_in() ) {
 // edit link
 } ?>

I think I need to get the current user info and do something with that.

Any help will be appreciated.

Answers 1

  • You can make use of the get_current_user_id(), get_the_author_meta('ID'), and get_edit_user_link() functions. Take the below snippet for instance:

    if( get_current_user_id() === get_the_author_meta('ID') ){
        printf( '<a href="%s">Edit Profile</a>', get_edit_user_link() );
    }
    

    get_current_user_id() will return int(0) if nobody is logged in, or the integer ID of the current user. This effectively removes the need for is_user_logged_in().

    get_the_author_meta('ID') will return string(0) "" if there's no page author (for instance on the home page), or the integer ID of the author if there is one, such as on the WordPress Author Archive page.

    You could also add is_user_logged_in(), but as I mentioned above, I think it's a bit redundant since get_current_user_id() essentially takes care of that for you:

    if( is_user_logged_in() && ( get_current_user_id() === get_the_author_meta('ID') ) ){
        printf( '<a href="%s">Edit Profile</a>', get_edit_user_link() );
    }
    

Related Questions