I posted this at wordpress.org as well, but I tend to find the feedback I get here very useful. I'm building a plugin to send SMS text messages, but that part isn't really important in this context.
Presented with the need to add a user meta data field for the phone number, after experimenting with a few different plugins which accomplish the task of creating custom db table fields, and managing the data therein, "I decided to go with Advanced Custom Fields. I can get the data I want for this simple SMS text plugin using the following code, but I feel like there must be a much cleaner, better recommended way to do it. Looking for feedback. Note, the desired data is the 10-digit number to be used for sending SMS text messages. The custom field was added as wp_usermeta.meta_value where wp_usermeta.meta_key is “sms_number”:
global $wpdb;
$res = $wpdb->get_results( $wpdb->prepare('SELECT wp_users.ID, wp_usermeta.meta_key, wp_usermeta.meta_value, wp_users.user_login, wp_users.user_email, wp_users.display_name, wp_users.user_nicename
FROM wp_users , wp_usermeta
WHERE wp_users.ID = wp_usermeta.user_id
AND wp_usermeta.meta_key = "sms_number"
ORDER BY wp_users.user_login'), ARRAY_N
);
$htmlOut = '';
if($res){
$htmlOut .= '<ol>';
foreach($res as $postKey => $postVal){
$valLength = count($res);
for($pi=0;$pi<$valLength;$pi++){
$htmlOut .= '<li class="'.$postKey.' meta_sms_item">$res['.$postKey.']['.$pi.'] : '.
$postVal[$pi].'</li>';
}
}
$htmlOut .= '</ol>';
}
echo "<h3>htmlOut is:</h3>\n".$htmlOut;
I get the following results, just testing for what the query results look like:
htmlOut is:
...
$res[0][5] : admin
$res[0][6] : admin
$res[1][0] : 3
$res[1][1] : sms_number
$res[1][2] : 1234567890
$res[1][3] : alycia21
$res[1][4] : domingo.sawayn@example.com
$res[1][5] : Rosalinda
$res[1][6] : ana38
$res[2][0] : 7
$res[2][1] : sms_number
$res[2][2] : 1234569870
$res[2][3] : gerhold.vern
$res[2][4] : ajaskolski@example.net
$res[2][5] : Claire
$res[2][6] : keshaun-farrell
$res[3][0] : 6
$res[3][1] : sms_number
$res[3][2] : 5683803132
$res[3][3] : lmitchell
...
$res[6][5] : Jade
$res[6][6] : amparo67
I could use $res[0][2] , $res[1][2] , $res[2][2]
… and so on to, for example, put the desired numbers in a dropdown selector. If I tweak the code and use $wpdb->get_row( )
and ARRAY_A , I get the following:
htmlOut is:
$res[ID] : 1
$res[meta_key] : sms_number
$res[meta_value] : 8142340768
$res[user_login] : admin
$res[user_email] : ajaxStardust@example.com
$res[display_name] : admin
$res[user_nicename] : admin
which I like a lot better, but I can’t figure out how to execute a query(1) to return multiple rows. In either instance, I used ARRAY_N, or ARRAY_A.
(1) that is, I can’t figure out how to use $wpdb->get_results() to use the field names as keys, which seems more convenient. Perhaps I don’t really need that?