• Resolved mightyx3n

    (@mightyx3n)


    Iam trying to make a shortcode that gives the current logged in users metadata
    but i cant get it to work.

    function usermeta($atts) {
        $default = array(
            'data' => '#',
        );
        $a = shortcode_atts($default, $atts);
    	return get_user_meta($user_id, $a['data'], true);
    						 
    }
    add_shortcode('usermeta', 'usermeta'); 
Viewing 3 replies - 1 through 3 (of 3 total)
  • Where are you getting the value of $user_id from? If that’s your code, it’s not being set anywhere, so there’s no user ID, and if there’s no user ID, you can’t get a meta value for it.

    If you want the user that is curerently logged in, you can use get_current_user_id() to get the ID of that user. You might alwao want to use is_user_logged_in() as well to check that there actually is a logged in user before you try to get any values for them.

    Hi mightyx3n,

    Hoe this will help you more.

    
    /*--------------------------------------------------------------
    [usermeta data="first_name,last_name"] = For specific fields
    [usermeta data="*"] or [usermeta] = For all fields
    -------------------------------------------------------------*/
    function my_current_usermeta($atts) {
        $default = array(
            'data' => '*',
        );
        $fields = shortcode_atts($default, $atts);
    	
    	if ( is_user_logged_in() ) {
    		$user_id = get_current_user_id();
    		$user_meta_data = array();
    		
    		if($fields['data'] == '*'){
    			$userdata = get_user_meta($user_id);
    			
    			foreach($userdata as $user_meta_key => $user_meta_val){
    				if(is_serialized($user_meta_val[0])){
    					$user_meta_data[$user_meta_key] = unserialize($user_meta_val[0]);
    				} else {
    					$user_meta_data[$user_meta_key] = $user_meta_val[0];
    				}
    			}
    		} else {
    			$fields = explode(',', $fields['data']);
    			
    			foreach($fields as $field){
    				$user_meta_data[$field] = get_user_meta($user_id, $field, true);
    			}
    		}
    		
    		return $user_meta_data;
    	} else {
    		return array();
    	}
    }
    add_shortcode('usermeta', 'my_current_usermeta');
    • This reply was modified 2 years, 5 months ago by Yui.
    • This reply was modified 2 years, 5 months ago by bcworkz. Reason: code format fixed
    Thread Starter mightyx3n

    (@mightyx3n)

    @catacaustic Thank you I got it working.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Trying to make User Meta Shortcode’ is closed to new replies.