Page 1 of 1

Access Custom Field Data

PostPosted: November 8th, 2010, 12:45 am
by ndavidson
To better help those searching the boards, I'm placing the usable code at the top of a new post, and will edit as it gets streamlined. The root post that shows the stages the code has gone through to get to this point is located at viewtopic.php?f=4&t=627 if you wish to follow along or add suggestions.

Ok, here's the controlled solution. What I didn't realize was that the data was entering MySQL serialized.

Code: Select all
$UserData = 3;//UserID;  to be set as a counter on a later loop edit

//create the query to the database
$query = "SELECT meta_value FROM wp_usermeta WHERE user_id='$UserData' && meta_key='wp_s2member_custom_fields'";

$results = $wpdb->get_col($query); //set the results to a usable variable
/*
## create an array to holdand unserialize the string,
## which places it into a key=>value pair with 'key' being
## the field name and 'value' being the value of the field
*/
$field_value_pairs = unserialize ($results[0]);

/*
# create a multidimensional array to connect all of
# the field=>value pairs to the user
*/
$Fields_By_User = array
(
$UserData => $field_value_pairs
);
/*
# To access the array you need to use the the keys of the
# user [$UserData] and the field names ['samplefield1']
# so if you had a field with the name 'city' you would get
# it's value buy typing $Fields_By_User[$UserData]['city'];
*/
echo $Fields_By_User[$UserData]['samplefield1'];


An un-commented example of how you would create a multidimensional array of users with field values would be: **Note, the loop is not tested and is for examples of use only.

Code: Select all
$user_query = $wpdb->get_col( $wpdb->prepare("SELECT $wpdb->users.ID FROM $wpdb->users " ));
$UserData = count($user_query);

   $Fields_By_User = array(
   
for($i=0;$i<$UserData;$i++)
{
   $query = "SELECT meta_value FROM wp_usermeta WHERE user_id='$i' && meta_key='wp_s2member_custom_fields'";
   $results = $wpdb->get_col($query);
   $field_value_pairs = unserialize ($results[0]);

      $i => $field_value_pairs
   
}  );


Not bad for 10 lines of code, eh? Anyone able to help me make it even better?