Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to construct manual custom fields out of a foreach array loop?

I have two custom fields which I hooked into the Ultimate Member - User Profile & Membership Plugin for Wordpress..

"username" => "Username",
"license_keys" => "License Key",

The foreach loop creates the fields perfectly, but I want to have the value of the license key field auto generated by $rand_str = generateRandomString();.

The first obvious thing is it's in a foreach loop, so both value fields on the outputted HTML become random strings and also change every time the page refreshes it changes to a new value.

I also tried if ($value = "License Key") statement to output a different $html if returned true, but since I'm in the foreach loop it applied the different $html to both fields anyhow.

So how can I control both fields outside the loop and apply individual logic to each?

/* make our new tab hookable */

add_action('um_account_tab__license', 'um_account_tab__license');

function um_account_tab__license($info) {
    global $ultimatemember;
    extract($info);

    $output = $ultimatemember->account->get_tab_output('license');
    if ($output) {
        echo $output;
    }
}

/* Finally we add some content in the tab */

add_filter('um_account_content_hook_license', 'um_account_content_hook_license');

function um_account_content_hook_license($output) {
    ob_start();

    function generateRandomString($length = 15) {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';

        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }

        return $randomString;
    }

    $custom_fields = [
        "username" => "Username",
        "license_keys" => "License Key",
    ];
    $rand_str = generateRandomString();

    foreach ($custom_fields as $key => $value) {
        $fields[$key] = array(
            'title' => $value,
            'metakey' => $key,
            'type' => 'select',
            'label' => $value,
        );

        global $ultimatemember;
        $id = um_user('ID');
        $field_value = get_user_meta(um_user('ID'), $key, true) ? : '';

        $html = '<div class="um-field um-field-'.$key.'" data-key="'.$key.'">
                    <div class="um-field-label">
                        <label for="'.$key.'">'.$value.'</label>
                    <div class="um-clear"></div>
                    </div>
                    <div class="um-field-area">
                        <input class="um-form-field valid "
                        type="text" name="'.$key.'"
                        id="'.$key.'" value="'.$field_value.'"
                        placeholder=""
                        data-validate="" data-key="'.$key.'">
                    </div>
                </div>';

        echo $html;
    }

    $fields = apply_filters( 'um_account_secure_fields', $fields, $id );
    $output .= ob_get_contents();
    ob_end_clean();

    return $output;
}

UPDATED CODE: The problem with this is that it returns only the last item in the $field_value array

foreach ($custom_fields as $key => $value) {
    $fields[$key] = array(
        'title' => $value,
        'metakey' => $key,
        'type' => 'select',
        'label' => $value,
    );

//$field_value = get_user_meta(um_user('ID'), $key, true) ? : '';
$field_value = [
    'username' => [
        'fieldvalue' => get_user_meta($id, $key, true) ? : '',
        //etc
    ],
    'license_key' => [
        'fieldvalue' => generateRandomString(),
        // etc
    ],
];


foreach ($field_value as $i => $field){
//echo um_profile_id();
$fieldsvalue[$i] = array(
    'field_value' => $field,
);

$html = '<div class="um-field um-field-'.$value['label'].'" data- 
key="'.$value['label'].'">
            <div class="um-field-label">
                <label for="'.$value['label'].'">'.$value['name'].'</label>
            <div class="um-clear"></div>
            </div>
            <div class="um-field-area">
                <input class="um-form-field valid "
                type="text" name="'.$value['label'].'"
                id="'.$value['label'].'" value="'.$field['fieldvalue'].'"
                placeholder=""
                data-validate="" data-key="'.$value['label'].'">
            </div>
        </div>';

}
echo $html;
}
like image 744
demo7up Avatar asked Feb 02 '26 00:02

demo7up


1 Answers

So they way your code is now you'd need to fill it with IFs and ELSEs to cater for each value in the $custom_fields array which is looped. As you need to set numerous variables based on which thing you have, such as if is username then do this else if is license_key do this.

This is a bad design and the answer to your question using that code would be a lot of changes.

So instead I suggest a slight refactor.

Adding another dimension to the $custom_fields array, so each initial key are your main items (license_key, username etc) then each value for those keys is a sub array containing all the values you need for each item.

For example:

$custom_fields = [
    'username' => [
        'name' => 'Username',
        'field_value' => set_user_meta(um_user('ID'), $key, true) ?: '',
        'label' => 'Username',
        'title' => 'Username',
        //etc
    ],
    'license_key' => [
        'name' => 'License Key',
        'field_value' => generateRandomString(),
        'label' => 'License Key',
        'title' => 'License Key',
        // etc
    ],
];

foreach ($custom_fields as $key => $values) {
    // The code
}

Then in your loop to satisfy the values you need, such as in the HTML, you'd access the same sub array key names for each one, such as $values['field_value'] and $values['label'] etc.
So on each loop it doesn't matter what the current item is in the loop (license_key, username etc), because you already set the data for each item before the loop, so the things in the loop are generic and named the same for all items (and obviously have different values).

You can remove items and add items to and from the array, and the loop will just use them as required.

like image 70
James Avatar answered Feb 03 '26 14:02

James



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!