Page 1 of 1

Getting Custom Field values on the frontend

PostPosted: May 24th, 2011, 4:10 pm
by totomobile
Is there an s2 function or a combination of functions that can get me the LABEL value for a custom s2member field?

Currently I am using

$custom_field = get_usermeta( bp_loggedin_user_id(), 'wp_s2member_custom_fields' );

but this only gets me the value and not the label of the custom field.

thanks
T

Re: Getting Custom Field values on the frontend

PostPosted: May 25th, 2011, 8:38 am
by Jason Caldwell
Thanks for the excellent question.

That's correct, by default you only get the field IDs in the associative array, and the values for each Custom Field key in the array. If you want the actual configuration options for each of these Custom Registration Fields, you can pull that from the options array, and match them up with the Unique ID ( i.e. the [id] key ).

Code: Select all
<?php
$fields_configured 
= json_decode($GLOBALS["WS_PLUGIN__"]["s2member"]["o"]["custom_reg_fields"], true);
print_r($fields_configured);
?>

Code: Select all
Array
(
[0] => Array
(
[section] => no
[sectitle] =>
[id] => country_code
[label] => Choose Country
[type] => text
[deflt] =>
[options] =>
[expected] =>
[required] => yes
[levels] => all
[editable] => yes
[classes] =>
[styles] =>
[attrs] =>
)

[1] => Array
(
[section] => no
[sectitle] =>
[id] => street_address
[label] => Street Address
[type] => text
[deflt] =>
[options] =>
[expected] =>
[required] => yes
[levels] => all
[editable] => yes
[classes] =>
[styles] =>
[attrs] =>
)

)


For example.
Code: Select all
<?php
$user_id 
= 123; /* A specific User ID. */
$street_address = get_user_field ("street_address", $user_id); /* Value of Custom Field: street_address */
$street_address_label = my_s2_custom_field_label ("street_address"); /* Might return: Street Address */
/*
Custom utility function to pull Labels.
*/
function my_s2_custom_field_label ($field_id)
    {
        foreach ((array)json_decode ($GLOBALS["WS_PLUGIN__"]["s2member"]["o"]["custom_reg_fields"], true) as $field_configured)
            {
                if ($field_configured["id"] == $field_id)
                    {
                        return $field_configured["label"];
                    }
            }
    }
?>

Re: Getting Custom Field values on the frontend

PostPosted: May 25th, 2011, 12:40 pm
by totomobile
Thanks Jason, I was actually looking for the value of the entry, aka, male| Male \n female | Female, so you would pass in male and it would return Male.

I saw this was stored in the [options] array inside the big array and I made an attempt to modify your function, but the way the data is returned it needs too much cleaning and verifying to be used in production code so I'm going to go about it an easier way (just caps the first letter of the value), but in future versions it would be nice to have this function available, aka s2_member_get_custom_field($value);

thanks
T

Re: Getting Custom Field values on the frontend

PostPosted: May 25th, 2011, 7:34 pm
by Jason Caldwell
Thanks for the follow-up.
Just to confirm, you want something like:
Code: Select all
s2member_get_custom_field($value) 

Returns Field Label? Like in the example above?

Re: Getting Custom Field values on the frontend

PostPosted: May 26th, 2011, 12:19 pm
by totomobile
Actually on second thought, it would make more sense if you pass in the custom field name, and it will return either value or label, something like:

s2member_get_custom_field('custom_gender');

Which would return "Male" if the customer had selected that (radio), or if it was a textbox it would just return the text. So just a way of grabbing custom fields on the frontend, thanks!!

Re: Getting Custom Field values on the frontend

PostPosted: May 26th, 2011, 3:40 pm
by Cristián Lávaque
You mean something like this?

Code: Select all
s2member_get_custom_field('favorite_color'); 
// outputs array('Favorite Color' => 'yellow') 

Re: Getting Custom Field values on the frontend

PostPosted: May 26th, 2011, 4:10 pm
by Jason Caldwell
Got it. Thanks guys.
@TODO: Custom Fields API function that does more than just collect value.

For the benefit of other readers:
Until then, please see the example above.

Re: Getting Custom Field values on the frontend

PostPosted: May 26th, 2011, 4:45 pm
by totomobile
Actually I may have caused some confusion, what I meant (implicitly in my head..) is to get the value for a *specific customer*. So it would be:

s2member_get_custom_field('favorite_color', $memberID);

which would return "Yellow" (which is the label for "yellow"). I hope this makes more sense now!

Re: Getting Custom Field values on the frontend

PostPosted: May 26th, 2011, 8:42 pm
by Cristián Lávaque
How about this function to get all the custom fields for a user? Returns associative array with field label and value pairs, defaults to current user if no user ID is given.

Code: Select all
function get_s2member_custom_fields($user_id = '') {
    $custom_fields = array();
    $values = get_user_option('s2member_custom_fields', $user_id);
    foreach ((array)json_decode($GLOBALS['WS_PLUGIN__']['s2member']['o']['custom_reg_fields'], true) as $field)
        $custom_fields[$field['label']] = isset($values[$field['id']]) ? $values[$field['id']] : '';
    return $custom_fields;
}
 


Do you see anything that can be improved in it, Jason? More efficient, versatile, or to prevent an error?

Re: Getting Custom Field values on the frontend

PostPosted: May 26th, 2011, 8:48 pm
by Jason Caldwell
That looks pretty solid to me. Nice work.

Re: Getting Custom Field values on the frontend

PostPosted: May 26th, 2011, 8:50 pm
by Cristián Lávaque
Cool, thank you. :)

Re: Getting Custom Field values on the frontend

PostPosted: May 26th, 2011, 9:00 pm
by Cristián Lávaque
I realized that the array my function outputs doesn't have the field IDs, making it harder to pick the one you want if you're not using them all. Here's an improved version for that:

Code: Select all
function get_s2member_custom_fields($user_id = '') {
    $values = get_user_option('s2member_custom_fields', $user_id);
    foreach ((array)json_decode($GLOBALS['WS_PLUGIN__']['s2member']['o']['custom_reg_fields'], true) as $field)
        $custom_fields[$field['id']] = array(
            'label' => $field['label'],
            'value' => isset($values[$field['id']]) ? $values[$field['id']] : '',
        );
    return $custom_fields;
}
 


Toto, since we're getting a value, I thought we may as well get them all, the way these arrays are and the WP function works, it's about the same work for the script, so it's better to just get everything into an array in one go and then use what you need.

You can use it like this

Code: Select all
$custom_fields = get_s2member_custom_fields();
echo 'My ', $custom_fields['favorite_color']['label'], ' is ', $custom_fields['favorite_color']['value'], '.';
  

Re: Getting Custom Field values on the frontend

PostPosted: May 26th, 2011, 9:13 pm
by Jason Caldwell
Very nice.

For the benefit of other readers.
By default, s2Member makes some of this possible without any hacks required.

Code: Select all
<?php
echo get_user_field
("street_address"); // Value of Custom Field with ID "street_address", for the current User.
?>

Or, if you're searching for details about a specific User:
Code: Select all
<?php
$user_id 
= 123;
echo get_user_field("street_address", $user_id); // Value of Custom Field with ID "street_address".
?>


get_user_field() is a function that comes with s2Member.

Re: Getting Custom Field values on the frontend

PostPosted: May 27th, 2011, 12:51 pm
by totomobile
Nice work guys! The get_user_option is what I was looking for from the start. Also the function that Cristian wrote is even better, however it won't work for radio buttons. In that case, we actually want the label for the radio button, and not the value.

As a test case:

Array ( [type] => radios [label] => Test Radio [id] => test_radio [required] => no [options] => value1|This is the label for value 1 value2|This is the label for value 2

So while the get_s2member_custom_fields() function that Cristian wrote will work fine for textareas, inputs, and checkboxes ( I tested these), it won't work for radio buttons, and perhaps dropdowns as they have the value|label setup instead of just value. So if I want to get the value(radio label) on the frontend, I have to try to parse out the "|" chars and do some sanitizing etc.

It's more of a nice to have, but in the next version of s2, if we could have a built in function which takes care of all this logic, that would be great.

thanks
T

Re: Getting Custom Field values on the frontend

PostPosted: May 27th, 2011, 6:51 pm
by Cristián Lávaque
You're right, Toto, I had not tried fields with more than one possible value. How about this then?

Code: Select all
function get_s2member_custom_fields($user_id = '') {
    $return = array();
    $user = get_user_option('s2member_custom_fields', $user_id);

    foreach ((array)json_decode($GLOBALS['WS_PLUGIN__']['s2member']['o']['custom_reg_fields'], true) as $field) {
        if (isset($user[$field['id']])) {
            $return[$field['id']]['label'] = $field['label'];

            if (empty($field['options']))
                $return[$field['id']]['value'] = $user[$field['id']];
            else {
                $field['options'] = strpos($field['options'], "\n") ? explode("\n", $field['options']) : (array)$field['options'];
                foreach ($field['options'] as $option) {
                    $option = explode('|', $option);
                    $options[$option[0]] = $option[1];
                }
                foreach ((array)$user[$field['id']] as $choice)
                    $return[$field['id']]['options'][] = array (
                        'label' => $options[$choice],
                        'value' => $choice,
                    );
            }
        }
    }
    return $return;
}
  


Let me know if you find any errors, I haven't really tested it much. :)

Re: Getting Custom Field values on the frontend

PostPosted: June 1st, 2011, 9:26 pm
by Cristián Lávaque
Toto, did you try the function? Would love to know if it helped you.

Re: Getting Custom Field values on the frontend

PostPosted: June 2nd, 2011, 12:37 pm
by totomobile
Hi Cristian, yes I tested it and it works. However, getting the info out of it is a bit indirect:

Code: Select all
$var get_s2member_custom_fields($user_id 1);
echo 
$var['user_preference']['options'][0]['label']; 


I think you've done enough to help though, anyone with basic coding skills can use or customize what you've put together. Perhaps for the next version of s2 you guys can have this as part of the core code as it'd be very useful!

thanks
T

Re: Getting Custom Field values on the frontend

PostPosted: June 2nd, 2011, 1:16 pm
by Cristián Lávaque
I'm glad it helped you.

I know the output may seem weird, but I actually thought a lot about it and how it'd be used.

I first did it array(field_label => field_value) or array(field_label => array(option_value => option_label)). This had a few problems because I had as the array keys data we want to use, which made it more uncomfortable and inefficient using array functions. The fields array didn't mention the field's name anywhere, only the label and value, so it was hard to use it. If you didn't know the option's value, then getting a specific label was impractical.

The way it is now it seems odd, but I think is more practical to use. Options has to be an array because fields with options can have multiple choices selected, not just one.

How do you find it indirect and how would you improve it? I'm very interested in your opinion, since you're using it.

By the way, you just enter the user's ID without defining a var in the function call:

Code: Select all
$s2_custom_fields = get_s2member_custom_fields(1); 

Re: Getting Custom Field values on the frontend

PostPosted: June 2nd, 2011, 4:19 pm
by totomobile
Hey Cristian, I didn't realize that you can have multiple options (aka multi select lists) so now the structure makes a lot more sense. My goal was to try to simplify the return structure, so that you just pass in the option value and only get a label/value array as the return value, but I realized your way is more flexible because it can be used to retrieve a single field, and can also be used to do a "listing" of all the user fields at the same time. So it's very flexible.

Also I did make a mistake there I just copied and pasted the $user_id =1 where it should have just been a single value being passed in.

Finally, this should probably be in a different thread but related.. I was doing some testing on 1.6 RC and found that radio option was missing! Maybe it's fixed now..

thanks
T

Re: Getting Custom Field values on the frontend

PostPosted: June 2nd, 2011, 7:32 pm
by Cristián Lávaque
Yeah, I didn't know about the options either, had not used those until you told me about it and I had to test each kind of custom profile field to have the function work well.

I'm glad you found the function good enough. Here's a slightly improved version for you:

Code: Select all
function get_s2member_custom_fields($user_id = '') {
    $return = array();
    $user = get_user_option('s2member_custom_fields', $user_id);

    foreach ((array)json_decode($GLOBALS['WS_PLUGIN__']['s2member']['o']['custom_reg_fields'], true) as $field) {
        if (isset($user[$field['id']])) {
            $return[$field['id']]['label'] = $field['label'];

            if (empty($field['options']))
                $return[$field['id']]['value'] = $user[$field['id']];
            else {
                $field['options'] = strpos($field['options'], "\n") ? explode("\n", $field['options']) : (array)$field['options'];
                foreach ($field['options'] as $option) {
                    $option = explode('|', $option);
                    $options[$option[0]] = $option[1];
                }
                foreach ((array)$user[$field['id']] as $choice)
                    $return[$field['id']]['options'][$choice] = $options[$choice];
            }
        }
    }
    return $return;
}
  


I guess it's fine to have the option's value as the key, since it's more useful to get a particular label. I realized that the way it was, it's uncomfortable to search the values to know which option we were looking for. This way, though, you can use the value as the key to know the label or search for the label to find its value.

Code: Select all
$s2_custom_fields = get_s2member_custom_fields($user_id); 

$option_label 
= $s2_custom_fields[$field_name]['options'][$option_value];

$option_value = array_search($option_label, $s2_custom_fields[$field_name]['options']);

foreach ($s2_custom_fields[$field_name]['options'] as $option_value => $option_label) {
    // ...
} 


Regarding the RC, exactly which one is it? There were two last week. Could you post a screenshot of the missing radio option?

Re: Getting Custom Field values on the frontend

PostPosted: July 31st, 2011, 10:41 pm
by ZebEl
I actually find this post very useful but I need your help just to wrap this part up Please.

However, as I've just basic knowledge of php, if I intend to implement your latest hack here above, where should I put it? Is this considered to be inserted in the template file (i.e. single.php) or do I need to hack into the function.php too?

Moreover, does ['id'] means that I have to enter my own custom field names here instead of id? For example, "customer_phone", "customer_zipcode", etc.?

Appreciate your concern.

P.S. For your information and just to give an example regarding getting values from custom fields, Advanced custom fields plugin has suggested different hacks regarding different fields. (http://plugins.elliotcondon.com/advanced-custom-fields/field-types/)