I'm trying to retrieve user information based on a URL within WordPress. I've setup a page template for each of the WordPress users on the site. I'd like to say "contact userfirst userlast" and display their email.

The URL structure is www.example.com/memberpage/username.

My code is:

function retrieve_member_name (){
  $current_member = get_user_by( 'slug', basename($_SERVER["REQUEST_URI"]) );

  if ( ! $current_member->exists() ) {
  if ($current_member->first_name){
    $fname = $current_member->first_name;
  } else {
    $fname = "";

  if ($current_member->last_name){
    $lname = $current_member->last_name;
  } else {
    $lname = "";
    $mname = $fname.' '.$lname;

    return $mname;

This works great, but if the member doesn't exist I get an error that I'm using exists() incorrectly. What is the proper way to test for $current_member when I call get_user_by()?

  • Is that a standard WordPress page? Is the author of the page you or the user mentioned? Keep in mind that this isn't usually how these things get built, and usually a page template or custom post type is used instead, with a theme template, rather than building everything out using shortcodes – Tom J Nowell Oct 29 '19 at 18:29
  • It's a custom page template. The problem is I'm working through another system so this is what I have available. The short code is working, it's the error response that I'm having troubles solving. I'm the author of the page. The username is derived from url base. – rudtek Oct 29 '19 at 18:35
  • If you can get the author of the page to be the user the page is about, then this becomes significantly easier. It would also be nicer to work with if you had a custom post type called members with a rewrite rule set to /memberpage. This would give you a free archive of members at /memberpage, an archive-members.php and single-members.php, allowing you to completely eliminate the need for setting up page templates, no longer cluttering up your pages section of the admin by moving them all out into a Members menu item, even making REST API requests simpler – Tom J Nowell Oct 29 '19 at 18:51

You should check if $current_member is empty, because get_user_by() would return false upon failure and a WP_User instance/object otherwise:

if ( empty( $current_member ) ) {
  return '';
|improve this answer|||||
  • 1
    This was it. I was checking the array improperly. Much appreciated. – rudtek Oct 29 '19 at 19:04

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.