PriMoThemes — now s2Member® (official notice)

This is now a very OLD forum system. It's in READ-ONLY mode.
All community interaction now occurs at WP Sharks™. See: new forums @ WP Sharks™

Display custom fields in posts.

s2Member Plugin. A Membership plugin for WordPress®.

Display custom fields in posts.

Postby MikeL » August 28th, 2010, 10:00 pm

Is there a way to display selected custom fields of registered users in a post? I want to place contact information for registerred users in a post that can be read by other users.
User avatar
MikeL
Registered User
Registered User
 
Posts: 6
Joined: August 28, 2010

Re: Display custom fields in posts.

Postby Jason Caldwell » August 30th, 2010, 9:50 am

Hi Mike. Thanks for the great question.

Yes. Take a look inside your Dashboard, under:
s2Member -> API Scripting

Be sure to upgrade to the latest release,
because s2Member v3.2.3+ includes support for Shortcodes as well.

Taken from the API Constants sub-section:

S2MEMBER_CURRENT_USER_FIELDS
This will always be a JSON encoded array, in (string) format. An empty JSON encoded array, in (string) format, if not logged in. This JSON encoded array will contain the following fields: id, ip, email, login, first_name, last_name, display_name, subscr_id, custom. If you've configured additional Custom Fields, those Custom Fields will also be added to this array. For example, if you configured the Custom Field: Street Address, it would be included in this array as: street_address. Custom Field references are converted to lowercase format, and spaces are replaced by underscores.

Code: Select all
<?php $fields = json_decode(S2MEMBER_CURRENT_USER_FIELDS, true); ?>
<?php echo $fields["first_name"]; ?> <?php echo $fields["last_name"]; ?>


Custom Fields are also included in the JSON decoded array.
( Displays a full list of all associative array elements. )
Code: Select all
<?php print_r(json_decode(S2MEMBER_CURRENT_USER_FIELDS, true)); ?>


s2member Shortcode Equivalents
( NEW ~ much easier )


[s2Get user_field="first_name" /]
[s2Get user_field="last_name" /]
[s2Get user_field="Website URL" /]
[s2Get user_field="My Custom Field Name" /]
[s2Get user_field="my_custom_field_name" /]
[s2Get user_field="any other WP_User property" /]

You can also pull details from the meta table.
[s2Get user_option="s2member_custom" /]
[s2Get user_option="s2member_subscr_id" /]
[s2Get user_option="s2member_last_payment_time" /]
[s2Get user_option="s2member_auto_eot_time" /]
[s2Get user_option="any other meta_key" /]
~ Jason Caldwell / Lead Developer
& Zeitgeist Movie Advocate: http://www.zeitgeistmovie.com/

Is the s2Member plugin working for you? Please rate s2Member at WordPress.org.
You'll need a WordPress.org account ( comes in handy ). Then rate s2Member here Image
.
User avatar
Jason Caldwell
Lead Developer
Lead Developer
 
Posts: 4045
Joined: May 3, 2010
Location: Georgia / USA

Re: Display custom fields in posts.

Postby MikeL » August 30th, 2010, 6:36 pm

The shortcodecodes work great for logged in users but what I want to do is display information for members not logged in. For instance on a particular post or page I want to display the Names, email addresses and phone numbers of users bob, joe, and jane. This is to be displayed publicly. Thus if they update their profile this information will automatically be updated.
User avatar
MikeL
Registered User
Registered User
 
Posts: 6
Joined: August 28, 2010

Re: Display custom fields in posts.

Postby Jason Caldwell » August 30th, 2010, 6:40 pm

Hi Mike. Thanks for reporting back.

I see what you mean.
s2Member does NOT provide this feature just yet.
It's on our @TODO list though.
viewtopic.php?f=4&t=618&p=2687&hilit=members+list#p2687

Until then, you might want to have a look at this plugin:
http://wordpress.org/extend/plugins/members-list/
~ Jason Caldwell / Lead Developer
& Zeitgeist Movie Advocate: http://www.zeitgeistmovie.com/

Is the s2Member plugin working for you? Please rate s2Member at WordPress.org.
You'll need a WordPress.org account ( comes in handy ). Then rate s2Member here Image
.
User avatar
Jason Caldwell
Lead Developer
Lead Developer
 
Posts: 4045
Joined: May 3, 2010
Location: Georgia / USA

Re: Display custom fields in posts.

Postby MikeL » August 30th, 2010, 7:13 pm

Had a quick look at members-list plugin and it's not quite what I needed either. It won't select specific users and it won't let me display s2member custom fields.

Well, thanks for your help but lets hope this gets put up near the top of the todo list.
User avatar
MikeL
Registered User
Registered User
 
Posts: 6
Joined: August 28, 2010

Re: Display custom fields in posts.

Postby Jason Caldwell » August 30th, 2010, 7:16 pm

Thanks for the feedback Mike.
~ Much appreciated.

I'll see what we can do.
~ Jason Caldwell / Lead Developer
& Zeitgeist Movie Advocate: http://www.zeitgeistmovie.com/

Is the s2Member plugin working for you? Please rate s2Member at WordPress.org.
You'll need a WordPress.org account ( comes in handy ). Then rate s2Member here Image
.
User avatar
Jason Caldwell
Lead Developer
Lead Developer
 
Posts: 4045
Joined: May 3, 2010
Location: Georgia / USA

Re: Display custom fields in posts.

Postby kingstocks » September 21st, 2010, 10:55 am

Hi all,
I hack in a script of my own
It works by the ID of the user,
then it pulls the info from the user meta table,
break the custom fields in to a array with the key being the name on your custom field.
the last thing is the table names on the default

I hope it help you out

<?php
$query = "SELECT ID, user_login FROM wp_users ORDER BY ID ASC";
$result = @mysql_query ($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
if($row['user_login'] != 'admin'){
$id = $row['ID'];
//getting the info form the system
$query = "SELECT meta_value FROM wp_usermeta WHERE user_id='$id' && meta_key='wp_s2member_custom_fields'";
$resultx = @mysql_query ($query);
$rowx = mysql_fetch_array ($resultx, MYSQL_NUM);
if(mysql_num_rows($resultx) != 0) {
$not = $rowx[0];
$str = str_replace("s:", "/", $not);
$str = str_replace("a:", "", $str);
$str = str_replace("{", "", $str);
$str = str_replace("}", "", $str);
$array_sucio = explode("/", $str);
$array_limpio = array();
$i = 0;
foreach ($array_sucio as $c) {
$array_limpio[$i] = $c;
$i++;
}
$done = count($array_limpio);
$a = 0;
for ($i = 1; ; $i++) {
if($done == $i){
break;
}
$start = stripos ( $array_limpio[$i] , ':');
$rest = substr($array_limpio[$i], 0, $start);
$start+= 2;
$finsh[$a] = substr($array_limpio[$i], $start, $rest);
$a++;
if ($i == 20) {break;}
}
$a=0;
$done = count($finsh);
$done = $done / 2;
for ($i = 1; ; $i++) {
$start = $finsh[$a];
$a++;
$end = $finsh[$a];
$fd[$start] = $end;
$a++;
if($done == $i){
break;
}
if ($i == 40) {break;}
}
?>
kingstocks
Guest User
Guest User
 

Re: Display custom fields in posts.

Postby MikeL » September 21st, 2010, 7:21 pm

I appreciate your effort but unfortunately I am not a programmer and I could not follow this. What I was hoping for was some simpler options that are part of s2member.
User avatar
MikeL
Registered User
Registered User
 
Posts: 6
Joined: August 28, 2010

Re: Display custom fields in posts.

Postby ndavidson » November 7th, 2010, 4:18 am

All right, you are on to something here. I've simplified it and made it more usable for my own purposes, but I think the plugin-lead programmer could make it even more applicable.

Code: Select all
//getting the info form the system
$query = "SELECT meta_value FROM wp_usermeta WHERE user_id='3' && meta_key='wp_s2member_custom_fields'";
$resultx = @mysql_query ($query);
$rowx = mysql_fetch_array ($resultx, MYSQL_NUM);
if(mysql_num_rows($resultx) != 0) {
$not = $rowx[0];

$custom_field_array = explode('"', $not);

// array [1] is the field name, array [3] is the value
echo "field name: " . $custom_field_array[1] . "<br/>";
echo "field value: " . $custom_field_array[3];
}


What I need it for is to be able to search all of my users based on custom field names and values for every user. Such as a custom field named 'city'.

For me to be able to do this I need to loop through all the users by count (like this)
Code: Select all
$query = $wpdb->get_col( $wpdb->prepare("SELECT $wpdb->users.ID FROM $wpdb->users " ));
$totalrows = count($query);

while grabbing the above code and placing it all in an array that I can then create a search function for that will locate all users that live in, say, Seattle.

What would be nice is to have a built in search feature for the plug-in that would allow for easy searching of any field, including the custom fields. My current modification would not be very efficient. Fortuanately I have a couple more days to work the concept before applying it to a live project.

to do:

    find a way to modify query using $wpdb->get_results
    create efficient loop
    create effective array to hold user data
    create search function for array

I'd love for Jason Caldwell to help me streamline this, or create a usable function for everyone!
Last edited by ndavidson on November 8th, 2010, 12:42 am, edited 3 times in total.
ndavidson
Guest User
Guest User
 

Re: Display custom fields in posts.

Postby ndavidson » November 7th, 2010, 4:18 am

Just a better notated variation that utilizes the built in Query feature of Wordpress. One less off the to-do list.

Code: Select all
//getting the info form the system

//create the query to the database
$query = "SELECT meta_value FROM wp_usermeta WHERE user_id='3' && meta_key='wp_s2member_custom_fields'";
/*
## deprecated in favor of default wordpress query
##
## $resultx = @mysql_query ($query);
## $rowx = mysql_fetch_array ($resultx, MYSQL_NUM);
## if(mysql_num_rows($resultx) != 0) {
## $not = $rowx[0];
*/
$resultx = $wpdb->get_col($query); //set the results to a usable variable
/*
##  Seperate the variable into an array of strings
##  using the quotation mark " as the seperator
*/
$custom_field_array = explode('"', $resultx[0]);
/*
## to avoid the data we don't want we need to skip every second number
## array [1] is the field name, array [3] is the value
## using the 1 and 3 logic, the next field/value pair will be [5] and [7],
## then [9] and [11] etc
*/
echo "field name: " . $custom_field_array[5] . "<br/>";
echo "field value: " . $custom_field_array[7];
ndavidson
Guest User
Guest User
 

Re: Display custom fields in posts.

Postby ndavidson » November 7th, 2010, 7:38 pm

Update using an array to store the field=>value pairs

Someone could likely create a far better array loop and, if so, please do and post

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

//getting the info form the system

//create the query to the database
$query = "SELECT meta_value FROM wp_usermeta WHERE user_id='$UserData' && meta_key='wp_s2member_custom_fields'";
/*
## deprecated in favor of default wordpress query
##
## $resultx = @mysql_query ($query);
## $rowx = mysql_fetch_array ($resultx, MYSQL_NUM);
## if(mysql_num_rows($resultx) != 0) {
## $not = $rowx[0];
*/
$resultx = $wpdb->get_col($query); //set the results to a usable variable
/*
##  Seperate the variable into an array of strings
##  using the quotation mark " as the seperator
*/
$custom_field_array = explode('"', $resultx[0]);
/*
## to avoid the data we don't want we need to skip every second number
## array [1] is the field name, array [3] is the value
## using the 1 and 3 logic, the next field/value pair will be [5] and [7],
## then [9] and [11] etc
*/
$FieldData[$custom_field_array[1]] = $custom_field_array[3]; //set first array field and value
$Remaining_array_count = count($custom_field_array) -4; //offset count to compensate for first value set
//iterate through the array to retrieve the remaining key/value pairs and insert them to the new array
for($i=3;$i<$Remaining_array_count;$i){
$FieldData[$custom_field_array[$i+2]] = $custom_field_array[$i+4];
$i = $i+2;
}
//set the resulting array into a multidimensional array using UserData
//to 'index' custom fields and contain them per user
$Fields_By_User = array
(
$UserData => $FieldData
);
//print the array to test results
print_r($Fields_By_User);

//print the count being iterated on original array
echo "<br/>".$Remaining_array_count;
ndavidson
Guest User
Guest User
 

Re: Display custom fields in posts.

Postby ndavidson » November 8th, 2010, 12:35 am

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?
ndavidson
Guest User
Guest User
 

Re: Display custom fields in posts.

Postby ndavidson » November 8th, 2010, 3:12 pm

Working on an annotated loop that only adds items to the array that match a search criteria

Code: Select all
//////////////////////////////
//     Match criteria       //
//////////////////////////////
$field_name = "samplefield1";     
$Match_1 = "";                           
$Match_2 = "";                           
//////////////////////////////
$user_query = $wpdb->get_col( $wpdb->prepare("SELECT $wpdb->users.ID FROM $wpdb->users " ));
$UserData = count($user_query); //UserID;  to be set as a counter on a later loop edit

for($t=0;$t<$UserData;$t++){
//create the query to the database
$query = "SELECT meta_value FROM wp_usermeta WHERE user_id='$t' && 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
*/

  if($field_value_pairs[$field_name] == Match_1)
  {
    //if match is found, add it to the array
   $Fields_By_User[$t] = $field_value_pairs;
  }
/* sample to match 2 fields 
if($field_value_pairs[$field_name] == Match_1 && $field_value_pairs[$field_name] == Match_2)
{$Fields_By_User[$i] = $field_value_pairs;}
*/
}//end for loop
/*
# 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'];
echo "<br/>";
print_r($Fields_By_User);


So what's really going on here?

We set the search criteria we want be typing the field name and field value we want to match.

Then we count all the users in the database and use the total as a counter

Next we use the counter to iterate through all the users and determine if any of the fields match.

If the fields match, we add the user and fields to an array we can use later

Pretty straight forward so far...

Once I get it all working efficiently and properly I can create a function and add it to the administration panel of s2Members as well as a sub-function allowing easy addition into posts/pages of results.

Right now it will search by custom field, but I'll likely think about adding a radio button in the administration to choose 'custom fields' or 'WP_Login' to search by. More searches could be added, but I'm not there yet.
ndavidson
Guest User
Guest User
 

Re: Display custom fields in posts.

Postby ndavidson » November 9th, 2010, 2:14 am

I finally got around to actually testing the code and made some modifications. I've refined the search to an array search which also makes it easier to refine the search further (in other words you can use regular expressions instead of string searches if you want)
Code: Select all
//////////////////////////////
//     Match criteria       //
//////////////////////////////
$field_name = "samplefield1";     
$Match_1 = "somethign to write here";                           
$Match_2 = "";                           
//////////////////////////////
$user_query = $wpdb->get_col( $wpdb->prepare("SELECT $wpdb->users.ID FROM $wpdb->users " ));
$UserData = count($user_query); //UserID;  to be set as a counter on a later loop edit

for($t=1;$t<=$UserData;$t++){
//create the query to the database
$query = "SELECT meta_value FROM wp_usermeta WHERE user_id='".$t."' && 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
*/
if(!empty($field_value_pairs)){
  //if($field_value_pairs[$field_name] = Match_1)
  if(in_array($Match_1,$field_value_pairs, TRUE))
  {
    //if match is found, add it to the array
   $Fields_By_User[$t] = $field_value_pairs;
  }
}

}//end for loop
/*
# 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'];
echo "<br/>";
print_r($Fields_By_User);
echo "<br/>";
ndavidson
Guest User
Guest User
 

Re: Display custom fields in posts.

Postby ndavidson » November 10th, 2010, 3:00 am

It appears that, since running json_decode() doesn't work I had to try something else to get the data. I then used unserialize().

Using the above method as well as a few different methods using OOP it appears there is no easy way to get more then the first record's data, period.

Now, any other field not encoded as the custom fields are can be retrieved in multiples, but that really doesn't solve my, or anyone's problems.

What goes wrong isn't retrieving all of the data, that I can do. As soon as a single custom field is unserialized it prevents further fields from being unserialized.

It's terrible to say, but these forums don't really come with guidance or answers so it looks like I'll be turning to Joomla for my CMS and AEC or some similar plug-in to achieve my needs.
ndavidson
Guest User
Guest User
 

Re: Display custom fields in posts.

Postby mrwweb » March 28th, 2011, 11:25 pm

So I've been struggling with this but have worked around a lot of it and I thought I'd share what I'd learned.

I'm pretty amazed that there isn't an easier way to do this yet, but I think what I've come up with is reasonably straight forward.

My first discovery was that I could in fact get to the data simply using get_userdata(). Oddly, as far as I can tell (i'm running WP3.1 and s2member 3.5.6), the data is not stored in an json array but rather just a regular array.

To get a custom s2member field for a specific user:

Code: Select all
$person = get_userdata( ID );
echo $person->wp_s2member_custom_fields["custom_field_key"]; 

"ID" is a user's ID and "custom_field_key" is whatever field you want to retrieve.

Next, I combined this with the new (as of WP 3.1) get_users() function:

Code: Select all
$nwfa_members = get_users();
foreach ($nwfa_members as $user) {
   $s2_data = get_userdata($user->ID);
   echo $user->display_name . ' - City: ' . $s2_data->wp_s2member_custom_fields["s2_city"];
}
 

In this case, I displayed "[USERNAME] - City: [CUSTOM_CITY_FIELD]".

I couldn't find anyway for get_users() to get the wp_s2member_custom_fields directly, hence the intermediate step of grabbing the user ID and then using get_userdata to get the s2 custom fields.

I am NOT a PHP programmer so it's possible that there are wildly better ways to do this. However, this seems like a step in the right direction, if nothing else.

Please give me feedback if you have any. I'm using this to put together a member directory on my site.
User avatar
mrwweb
Registered User
Registered User
 
Posts: 1
Joined: March 28, 2011


Return to s2Member Plugin

Who is online

Users browsing this forum: Google [Bot] and 0 guests

cron