0

I have looked for an answer, and couldn't find a clear and relevant answer yet.

I want to add more attribute to the users not to display, but only store information about them. The information will be used for a background function. I know that usermeta is used to add more attributes, and I know how to access the already existing information, but I don't know how to add/create new attributes.

This piece of information can be a null string by default for every user and modified if the user enters information.

I'd appreciate any kind of help since I'm new at Wordpress. Thanks!

1

The easiest trick is to use the user_contactmethods - the fields don't actually have to be contacts, but WordPress will do all the leg work for you (displaying the fields & saving the data):

function wpse_183763_user_contactmethods( $methods, $user ) {
    $methods['my_field_1'] = 'My Label For Field 1';
    $methods['my_field_2'] = 'My Label For Field 2';

    return $methods;
}

add_filter( 'user_contactmethods', 'wpse_183763_user_contactmethods', 10, 2 );

If you add this code to a plugin or your functions.php, you'll see the new fields when editing your profile. To get the values, just use the meta API:

// With a user ID
echo get_user_meta( $user_id, 'my_field_1', true );

// Or with a WP_User object
echo $user->my_field_1;
  • I really appreciate your answer, but what do parameters 10 and 2 stand for in the add_filter function? – blueseal Apr 10 '15 at 19:14
  • 10 is the priority (for a filter/action that has multiple functions hooked to it, they are executed in order from the lowest number to the highest), and 2 is the number of accepted arguments. Check out the codex. – TheDeadMedic Apr 10 '15 at 19:25
  • I added your exact code to my functions.php(only changed the field names) and made sure this ran in a template: update_user_meta($user_id, 'last_booked_lesson', 'Languages of Europe'); But I don't see any row created in the database. Do I need to do one more thing? – blueseal Apr 10 '15 at 20:32
  • Are you defining $user_id? It sounds from your comment that my answer isn't actually what you need. My code will add fields to the user profile, but if you just need to read/save meta, just use the *_user_meta functions. – TheDeadMedic Apr 11 '15 at 9:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.