1

I'd like to retrieve the meta_key names, (and values), for all wp_usermeta records for 1 specific user. While I can do this by querying the database with the proper SQL I can't get it with the get_user_meta function call.

1. Using '$wpdb->get_result'

$all_user_meta = $wpdb->get_results ( "SELECT * FROM wp_usermeta WHERE user_id = $user_id " );
if ( !empty($all_user_meta) )
{
     $cnt = 0 ;      
     $idx = -1 ;      
     foreach ( $all_user_meta as $one_meta )
     {
           $meta_key = $one_meta->meta_key ;
           echo('Meta Key: '.$meta_key.'<br/>');

           // THIS WORKS !!
     }
}

2. Using Wordpress function Call

$user_meta_array = get_user_meta($user_id) ;
foreach($user_meta_array as $user_meta)
{
    $meta_key = $user_meta->meta_key ;
    echo('Meta Key: '.$meta_key.'<br/>');

     // THIS DOES NOT WORK !!
     // The loop does execute the proper number of times
}

1 Answer 1

0

I just figured it out. I didn't understand associative arrays properly and after doing more research I came up with the following that works:

$user_id = 6 ;
$user_meta_array = array() ;

/* the following Wordpress function outputs an associative array  */

$user_meta_array = get_user_meta($user_id);

$meta_cnt = -1 ;

/* You need the following loop structure to output nicely */

foreach($user_meta_array as $user_meta =>$mk)
{
   $meta_cnt = $meta_cnt + 1 ;
   echo('Meta Key: '.$user_meta.'<br/>');

/* Each wp_usermeta key can have multiple values  */

   $meta_vals_found = false ;
   foreach($mk as $mk_each)
   {
      if(!empty($mk_each))
      {
         $meta_vals_found = true ;
         echo('Meta Value----> '.$mk_each.'<br/>');
      } 
   }
   if(!$meta_vals_found)
   {
       echo('----> No Meta Values Entered<br/>');
   }   
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.