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
}
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
}
Share
Improve this question
edited Mar 24, 2020 at 2:15
WordPress Speed
2,2833 gold badges19 silver badges34 bronze badges
asked Mar 23, 2020 at 18:03
oldsportbikeroldsportbiker
111 bronze badge
1 Answer
Reset to default 0I 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/>');
}
}