I am trying to get a user by metakey
:
$user = get_users( array (
'meta_key' => 'token',
'meta_value' => $token,
'orderby' => 'meta_value',
'order' => 'DESC',
'number' => '10',
) );
This returns empty array, but there is a user with that meta key value.
$user = reset(
get_users(
array(
'meta_key' => 'token',
'meta_value' => $token,
'number' => 1,
'count_total' => false
)
)
);
This returns false
with a notice:
only variables should be passed by reference in
, but still there is a user with that value for the meta.
I need just to select a user FROM the current blog (to check, is it exists ) by metavalue. User in WordPress NETWORK, which is not attached to the current blog.
I am trying to get a user by metakey
:
$user = get_users( array (
'meta_key' => 'token',
'meta_value' => $token,
'orderby' => 'meta_value',
'order' => 'DESC',
'number' => '10',
) );
This returns empty array, but there is a user with that meta key value.
$user = reset(
get_users(
array(
'meta_key' => 'token',
'meta_value' => $token,
'number' => 1,
'count_total' => false
)
)
);
This returns false
with a notice:
only variables should be passed by reference in
, but still there is a user with that value for the meta.
I need just to select a user FROM the current blog (to check, is it exists ) by metavalue. User in WordPress NETWORK, which is not attached to the current blog.
Share Improve this question asked Jul 6, 2019 at 23:27 gdfgdfggdfgdfg 1721 silver badge15 bronze badges 1 |1 Answer
Reset to default 1This is the problem:
$user = reset(
get_users(
reset
expects a reference to an array, and there's no mechanism for error checking. So even if it finds the user, you're misusing the return value.
It might be possible to adjust this to use references properly, but references in PHP are something best avoided, and there are better options out there for getting the first item in an array in PHP.
This would work better, and provide a chance to check for error values or empty arrays:
$users = get_users(... );
$user = reset( $users );
This would work even better as it doesn't modify the array, and it runs in O(1) time so it's the same cost no matter how large the array gets:
$users = get_users(...);
$user = array_pop(array_reverse($users));
This one also works in PHP 5.4+:
$users = get_users(...);
$user = array_values($users)[0];
All of them, including what you have right now, will require you to do this:
if ( empty( $users ) ) {
// nothing was found, print an error message and abort
}
get_users
into areset
call, can you explain why? It's not good practice to nest function calls as it makes it difficult to debug problems. Have you verified$token
actually contains the correct value? How are you error checking the value ofget_users
to make sure it isn't aWP_Error
object with an error message? – Tom J Nowell ♦ Commented Jul 7, 2019 at 1:55