How to create virtual pages with information from user meta profile fields?

Before answer, a side note: what you want can be done a in a lot simpler and more performant way just creating a real post type: register a cpt, maybe not public (so no ui is showed on dashboard), and on user profile saving/updating just create/update a cpt entry.

Doing so you do not need any external class and you can just use the core wp functions, to show all member pages, show single member page, link them and any other things you need.

As bonus you can also make use of the template hierarchy and have a lot more flexibility.

One my personal rule of thumb is: “never write code for custom features when core can do same thing”. In your case core features don’t do the same, do it better and simpler.

However, this is a Q&A site, you asked a question and this is the answer:

the dj_create_virtual function must be changed in something like this:

function dj_create_virtual() {
  $url = trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), "https://wordpress.stackexchange.com/");
  if ( strpos($url, 'member-') === 0 ) {
    $user_nicename = str_replace('member-', '', $url);
    $user = get_user_by( 'slug', $user_nicename );
    $user_info = array_map( function( $a ){ return $a[0]; }, get_user_meta( $user->ID ) );
    $args = array(
      'slug' => 'member-' . $user_nicename,
      'title' => $user_info['first_name'] . ' ' . $user_info['last_name'],
      // following is just an example
      'content' => 'This is the page for:' . $user_info['first_name'] . ' ' . $user_info['last_name']
    );
    $pg = new DJVirtualPage($args);
  }
}
add_action('init', 'dj_create_virtual');

and your members_listing function need just a little edit:

function members_listing( $department ) {
   $members = get_users( array( 'meta_key' => 'department', 'meta_value' => $department ) ); 
   usort($members, create_function('$a, $b', 'return strnatcasecmp($a->last_name, $b->last_name);'));
   echo '<div id="memberlist"><ul>';
   foreach ( $members as $member ) {
      echo '<li>';
      echo get_avatar($member->ID);
      $user_info = array_map( function( $a ){ return $a[0]; }, get_user_meta( $member->ID ) );
      $fullname = $user_info['first_name'] && $user_info['first_name'] ? $user_info['first_name'] . ' ' . $user_info['last_name'] : $member->display_name;
      printf( '<div class="authname"><a href="https://wordpress.stackexchange.com/questions/112987/%s">%s</a></div></li>', home_url('/member-' . $member->user_nicename), $fullname);
   }
   echo '</ul></div>';
}

Leave a Comment