gianghl1983
3/19/2019 - 12:15 PM

A WordPress custom shortcode to display a piece of user metadata from the wp_usermeta table. Relies on Ultimate Member plugin

A WordPress custom shortcode to display a piece of user metadata from the wp_usermeta table. Relies on Ultimate Member plugin

/* Create new shortcode for quickly displaying user metadata.
*** NOTE: This only works if you have the Ultimate Member plugin installed. 
*** Use like regular wordpress shortcodes. Enter [USERMETA user_id="*id*" meta="*field_name*"] (replace *id* and *field_name* with actual values)
*** If you use it on an Ultimate Member profile page/tab, it will use the user currently being viewed. 
*** On other pages, you must include the "user_id" within the shortcode. 
*/
//Add the shortcode to WordPress
add_shortcode('USER_META', 'user_meta_shortcode_handler');

//create the function referenced by the add_shortcode()
function user_meta_shortcode_handler($atts,$content=null){

  //get profile id
  $profile_id = um_profile_id();
  //if profile ID found, it means we're on an Ultimate Member profile page. So use the profile_id of the user being viewed. 
  if($profile_id) {
    // return the specified metadata
    return esc_html(get_user_meta($profile_id, $atts['meta'], true));
  }

  else {
    //use the user_id and return that user's metadata
    return esc_html(get_user_meta($atts['user_id'], $atts['meta'], true));
  }
}