Get user input from a form

Use wp-admin/admin-post.php as form action handler, and bind your custom function as callback to that.

A simple example for email updates. We will use a shortcode named [userform] here, but you can use a template too.

add_shortcode( 'userform', 'wpse_75723_userform' );
add_action( 'admin_post_update_user_email', 'wpse_75723_update' );

/**
 * Create the form.
 */
function wpse_75723_userform()
{
    $here = esc_url( home_url( $_SERVER['REQUEST_URI'] ) );

    if ( ! is_user_logged_in() )
        return  'You have to <a href="' . wp_login_url( $here ) . '">log in</a> to use this page.';

    $action  = admin_url( 'admin-post.php');
    $user_id = get_current_user_id();

    return "<form method='post' action='$action'>
    <input type="hidden" name="action" value="update_user_email">
    <input type="hidden" name="redirect" value="$here">
    <input type="hidden" name="user_id" value="$user_id">
    <input type="email" name="email" size="15">
    <input type="submit">
    </form>";
}

/**
 * Update user email
 */
function wpse_75723_update()
{
    if ( ! isset ( $_POST['user_id'] ) )
        die( 'no id' );

    $user_id = absint( $_POST['user_id'] );

    if ( ! current_user_can( 'edit_user', $user_id ) )
        die( 'not allowed' );

    if ( ! isset ( $_POST['email'] ) )
        die( 'no email' );

    if ( ! is_email( $_POST['email'] ) )
        die( 'invalid email' );

    $user = get_userdata( $user_id );

    if ( empty ( $user->user_login ) )
        die( 'user denied' );

    global $wpdb;

    $wpdb->query(
        $wpdb->prepare(
            "UPDATE {$wpdb->users} SET user_email = %s WHERE user_login = %s",
            $_POST['email'],
            $user->user_login
        )
    );

    $location = isset ( $_POST['redirect'] )
        ? urldecode( $_POST['redirect'] )
        : home_url( "https://wordpress.stackexchange.com/" );

    wp_redirect( $location, 303 );
    exit;
}

Inserting …

[userform]

… into a page will produce a basic form:

enter image description here

The user can change her/his email address here.

To understand what variables are available and where they are stored look at these files:

  • wp-admin/user-edit.php
  • wp-admin/includes/user.php and
  • wp-includes/user.php

The tables users and user_meta are worth a look too if you want to send plain SQL queries.

Leave a Comment