Display User Meta

This functions adds a shortcode which allows you to display meta fields that a specific/the current user has.

Parameters:

  • user_id – id of the user which you want to retrieve the meta from. Leave empty if it should be equal to the current user.
  • key – meta key of the field that you want to retrieve
  • wpautop = “on” – this is used for textarea or wysiwyg fields
  • size = “100” – this is used for the avatar field to specify the size of it

Shortcode:

[user_meta key=”avatar”]

You can add this shortcode to your website using the Customization Toolbox add-on.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/*
 * List user meta using a shortcode
 */
add_shortcode('user_meta', 'user_meta_shortcode_handler');
function user_meta_shortcode_handler($atts,$content=null){
 
	if ( !isset( $atts['user_id'] ) ){
		$user = wp_get_current_user();
		$atts['user_id'] = $user->ID;
	}
	if ( !isset( $atts['size'] ) ){
		$atts['size'] = '50';
	}
	if ( !isset( $atts['pre'] ) ) {
		$atts['pre'] = '';
	}
	if ( !isset( $atts['post'] ) ) {
		$atts['post'] = '';
	}
	if ( !isset( $atts['wpautop'] ) ) {
		$atts['wpautop'] = '';
	}
 
 
	$user = new WP_User($atts['user_id']);
 
	if ( !$user->exists() ) return;
 
	if( $atts['key'] == 'avatar'){
		return $atts['pre'] . get_avatar( $user->ID, $atts['size']) . $atts['post'] ;
	}
	if ( $user->has_prop( $atts['key'] ) ){
		if ($atts['wpautop'] == 'on'){
			$value = wpautop( $user->get( $atts['key'] ) );
		} else {
			$value = $user->get( $atts['key'] );
		}
	}
 
	if (!empty( $value )){
		return $atts['pre'] . $value . $atts['post'] ;
	}
 
	return;
}