WordPress update_user_meta not saving

I have multiple additional usermeta fields created and working via the backend with WordPress.

However, I’m trying to create a simple form that allows people to click a button that saves a field to their profile. I’ve been all through StackOverflow, wordpress.stackexchange.com, and the wordpress.org forums. People seem to have this working, but I can’t do the same.

Read More

Any help anyone can throw my way is much appreciated.

Here’s my code, in functions.php:

function my_function() {
if (is_user_logged_in()) {
    global $post;
    if (has_badge()) {
        $current_user = wp_get_current_user();
        $badge_ID = get_post_meta($post->ID, 'badge_id', true);
        $badge_check = $current_user->$badge_ID;            
        $badge_id_1289 = get_user_meta( $current_user->ID, 'badge_id_1289', true);

        return '<form name="update_badges" action="#" method="POST">

    <fieldset>
    <label for="'.$badge_ID.'">Badge Name</label>
    <input type="text" id="'.$badge_ID.'" name="'.$badge_ID.'" value="'.$badge_ID.'" />
    </fieldset>

    <button type="submit">Claim Badge</button>
</form>';
    update_user_meta( $current_user->ID, 'badge_id_1289', $_POST['badge_id_1289'] );

} 
add_shortcode('subscribe','my_function');

$badge_ID is taken from a custom field in the post this shortcode is added to, and I have confirmed it’s working correctly (it shows as the value in the input field, the “for” in the label, etc.)

I get nothing. The form submits, the page reloads, but nothing gets saved to the database and therefor nothing shows up in the user’s profile.

Any idea what I might need to do additionally with update_user_meta, or if this is a shortcode problem?

Related posts

Leave a Reply

1 comment

  1. @brasofilo was correct, the issue was that I was calling user_update_meta before the return. Here’s the correct version:

    function my_function() {
        if (is_user_logged_in()) {
        global $post;
        if (has_badge()) {
            $current_user = wp_get_current_user();
            $badge_ID = get_post_meta($post->ID, 'badge_id', true);
            $badge_check = $current_user->$badge_ID;            
            $badge_id_1289 = get_user_meta( $current_user->ID, 'badge_id_1289', true);
            update_user_meta( $current_user->ID, 'badge_id_1289', $_POST['badge_id_1289'] );
            return '<form name="update_badges" action="#" method="POST">
            <fieldset>
                <label for="'.$badge_ID.'">Badge Name</label>
                <input type="text" id="'.$badge_ID.'" name="'.$badge_ID.'" value="'.$badge_ID.'" />
            </fieldset>
    
            <button type="submit">Claim Badge</button>
        </form>';
    } 
    add_shortcode('subscribe','my_function');