admin管理员组

文章数量:1122846

I am attempting to get meta data in a list of WP users using this code, but am unable to retrieve the meta data:

$args = array(
    'meta_key' => 'last_name',
    'orderby' => 'meta_value',
    'order' => 'ASC'
    );              

$users = get_users( $args );
                
foreach ( $users as $user ) {
    $user_id = $user->ID;
    $post_count = count_user_posts($user_id); 
                        
    if( $post_count > 0 ){                                          
        $user_meta = get_user_meta( $user_id );
        echo ' ID: ' . $user_id . ' | ';
        var_dump($user_meta);
        echo '<br />';
    }
}

This is what the script returns:

ID: 6460 | array(0) { }
ID: 6468 | array(0) { }
ID: 6472 | array(0) { }
ID: 6474 | array(0) { }
etc...

However, when I try to fetch the user meta data outside of the loop, it works fine:

$user_id = 6460;
var_dump(get_user_meta( $user_id ));

Any idea what I'm doing wrong?

I am attempting to get meta data in a list of WP users using this code, but am unable to retrieve the meta data:

$args = array(
    'meta_key' => 'last_name',
    'orderby' => 'meta_value',
    'order' => 'ASC'
    );              

$users = get_users( $args );
                
foreach ( $users as $user ) {
    $user_id = $user->ID;
    $post_count = count_user_posts($user_id); 
                        
    if( $post_count > 0 ){                                          
        $user_meta = get_user_meta( $user_id );
        echo ' ID: ' . $user_id . ' | ';
        var_dump($user_meta);
        echo '<br />';
    }
}

This is what the script returns:

ID: 6460 | array(0) { }
ID: 6468 | array(0) { }
ID: 6472 | array(0) { }
ID: 6474 | array(0) { }
etc...

However, when I try to fetch the user meta data outside of the loop, it works fine:

$user_id = 6460;
var_dump(get_user_meta( $user_id ));

Any idea what I'm doing wrong?

Share Improve this question asked Jun 3, 2024 at 20:59 zeldatronzeldatron 1
Add a comment  | 

1 Answer 1

Reset to default 0

Use this code instead-

$args = array(
    'meta_key' => 'last_name',
    'orderby' => 'meta_value',
    'order' => 'ASC'
);              

$users = get_users( $args );
                
foreach ( $users as $user ) {
    $user_id = $user->ID;
    $post_count = count_user_posts( $user_id ); 
                        
    if ( $post_count > 0 ) {                                          
        $user_meta = get_user_meta( $user_id, '', true );
        echo 'ID: ' . $user_id . ' | ';
        var_dump( $user_meta );
        echo '<br />';
    }
}

Ensure the get_user_meta function retrieves all meta keys by passing an empty string as the meta key and setting the third parameter to true to return the data in a single array.

本文标签: user metawpusermeta doesn39t return data in a foreach loop