How/where to add custom user profile/meta fields

I’m trying to add custom user profile/meta data to users. However, I’m unsure of correct way and location to add the code. I’d like to include it directly in the functionality of the theme rather than use a plugin as I don’t like the plugins I’ve tested. Essentially, I want additional form fields when editing user profiles on the back end.

I tried to follow this tutorial – http://www.paulund.co.uk/add-custom-user-profile-fields – for adding a few extra user meta fields. Typically I’d add this to my functions.php file, but in the Sage workspace I’m still unsure. I’ve added the code to extras.php file, but the new fields do not show up when editing user profiles.

What am I doing wrong? Is there a particular file to edit or specific way to add code that is best for this type of functionality? Or am I just being dumb and there’s a perfectly good plugin for this?

As always, any help and/or insights are greatly appreciated.

– Patrick

Are you passing the namespace with your hook function name?

Yup. That must have been it. My mistake. For reference, here’s the final code.

do_action( 'show_user_profile', $profileuser );
do_action( 'edit_user_profile', $profileuser );

add_action( 'show_user_profile', __NAMESPACE__ . '\\add_extra_user_meta_fields' );
add_action( 'edit_user_profile', __NAMESPACE__ . '\\add_extra_user_meta_fields' );

function add_extra_user_meta_fields( $user )
{
    ?>
        <h3>Other User Information</h3>
        <table class="form-table">
            <tr>
                <th><label for="primary_market">Primary Market</label></th>
                <td><input type="text" name="primary_market" value="<?php echo esc_attr(get_the_author_meta( 'primary_market', $user->ID )); ?>" class="regular-text" /></td>
            </tr>
        </table>
    <?php
}

add_action( 'personal_options_update', __NAMESPACE__ . '\\save_extra_user_meta_fields' );
add_action( 'edit_user_profile_update', __NAMESPACE__ . '\\save_extra_user_meta_fields' );

function save_extra_user_meta_fields( $user_id )
{
    update_user_meta( $user_id,'primary_market', sanitize_text_field( $_POST['primary_market'] ) );
}

Does this seem legit? It’s working now, so that’s a good sign.

– Patrick