Search code examples
phpwordpressfrontenduser-profile

WordPress Update User Meta Front End Profiles


i created a plugin to create a user profile page. On this the user is able to update custom meta information through a form. Here is my function:

// Function to edit User Meta

function personalfragebogen_konto_bearbeiten() {

global $current_user;

// Get User Meta

$strasse = get_user_meta( $current_user->ID, '_strasse', true);

// Create Form

<form name="personalfragebogen" action="" method="POST">

    <span class="full" >
        <span class="two_fifth first">
            <h3><?php _e( 'Straße:', 'themesdojo' ); ?></h3>
        </span>

        <span class="three_fifth">
            <input type="text" name="strasse" id="strasse" value="<?php echo $strasse; ?>" class="input-textarea"/>
        </span>
    </span>

<button type="submit">Speichern</button>

</form>

// Get New User Meta

$strasse = $_POST['strasse'];

// Update/Create User Meta

update_user_meta( $current_user->ID, '_strasse', $strasse); 

// Add Hook

add_action( 'personalfragebogen_init', 'personalfragebogen_konto_bearbeiten');

function personalfragebogen_init() {
    do_action('personalfragebogen_init');
}

Everything works fine, except of one thing. When I submit the form the data saves to the database and the page refreshes. But now on my refreshed page the form is empty. When refresh the page again then the data is shown. Whats the problem about this?

Thank you in advance!


Solution

  • Something like this could work...

    <?php
    // Function to edit User Meta
    function personalfragebogen_konto_bearbeiten() {
    
        global $current_user;
    
        // Get New User Meta
        if(isset($_POST['strasse'])) {
            $strasse = $_POST['strasse'];
            // Update/Create User Meta
            update_user_meta( $current_user->ID, '_strasse', $strasse);     
        else {
    
            // Get User Meta
            $strasse = get_user_meta( $current_user->ID, '_strasse', true);
        }
    
    
    ?>
    
        <form name="personalfragebogen" action="" method="POST">
    
            <span class="full" >
                <span class="two_fifth first">
                    <h3><?php _e( 'Straße:', 'themesdojo' ); ?></h3>
                </span>
    
                <span class="three_fifth">
                    <input type="text" name="strasse" id="strasse" value="<?php echo $strasse; ?>" class="input-textarea"/>
                </span>
            </span>
    
        <button type="submit">Speichern</button>
    
        </form>
    <?php
        }
    
    // Add Hook
    
    add_action( 'personalfragebogen_init', 'personalfragebogen_konto_bearbeiten');
    
    function personalfragebogen_init() {
        do_action('personalfragebogen_init');
    }