I want to
echoa list of all users who have that field; in other
words, a list of each user’s name, phone number, and the quantity.
Try this, which is based on your 1st snippet:
( and this is all you need; no need for the $wpdb->get_col() snippet )
$user_query = new WP_User_Query( array( 'meta_key' => 'sms_subscriber' ) );
$users = $user_query->get_results();
if (!empty($users)) {
echo '<h3>SMS Subscribers (' . $user_query->get_total() . ')</h3>';
echo '<ul>';
foreach ($users as $user){
// this one uses the magic __get() method in WP_User, i.e. $user-><meta key>
// echo ' <li>' . $user->display_name . " $user->sms_subscriber" . '</li>';
$sms_subscriber = get_user_meta( $user->ID, 'sms_subscriber', true );
echo ' <li>' . $user->display_name . " $sms_subscriber" . '</li>';
}
echo '</ul>';
}
Things to note:
-
You can use
get_user_meta()to retrieve the value of a user meta.Alternatively,
WP_Userhas a magic__get()method which you can use to get a meta value without having to use the above function, but only to get a single meta value (regardless if that value is a string/text, number, array, etc.). So for example, you could use$user->sms_subscriberlike you could see in the code I commented out above. -
To get the “quantity” or
sumas you said it, which is the total number of users that matched your query arguments, you can useWP_User_Query::get_total().If you just wanted to count the number of items in
$users(i.e. the 1st page of the query’s results — the results can be paginated using thenumberargument), then you’d usecount( $users )in place of the$user_query->get_total().