0

I want to give user ability to update their nickname from front end using wp_update_user and shortcode. The code below is working.

      add_shortcode('user-profile', 'get_current_user_prof');

      function get_current_user_prof() {
      global $current_user;
      get_currentuserinfo();
            if(is_user_logged_in()) {
$tableuserinf = "<form method='post' action='#'><table><tbody>";
$tableuserinf .= "<tr><td>Nickname:</td><td><input type='text' name='fepusernick' value='". $current_user->nickname ."'/></td></tr>";
$tableuserinf .= "</tbody></table><button>Submit</button></form>";

          $user_id = 1;
    $nicksname = $_POST['fepusernick'];
    wp_update_user( array ( 'ID' => $user_id, 'nickname' => $nicksname ) ) ;
                return $tableuserinf;
}
          }

The only problem with the code above is its field showing the previous value of the database after update success. And will only retrieve the database data after the page is refreshed. This will confuse user. How to solve that problem?

  • 1
    You're returning the HTML before you can even read the $_POST value. Try reading it first. If it's not set then return the form, if it is update the user and return a success message. On a side note, don't mangle together copy and paste's without learning some basic PHP first. – Twifty Sep 21 '13 at 8:36
1

You have, at least, three wrong things in your code. First. You are "returning" before you try to update the user info, so the wp_update_user() function is not executed. Second, you have the user ID hardcoded, so you always trying to modify the nickname of the user with ID = 1

 return $tableuserinf;
 $user_id = 1;
 $nicksname = $_POST['fepusernick'];
 wp_update_user( array ( 'ID' => $user_id, 'nickname' => $nicksname ) ) ;

Should be:

$user_id = $current_user->ID;
$nicksname = $_POST['fepusernick'];
wp_update_user( array ( 'ID' => $user_id, 'nickname' => $nicksname ) ) ;
return $tableuserinf;

You can go further and make some checks:

$user_id = $current_user->ID;
// Not sure if sanitize_user() is needed or is executed by wp_update_user(). Anyway, it doesn't hurt
$nicksname = isset($_POST['fepusernick']) ? sanitize_user($_POST['fepusernick']) : '';
//check if new nickname is different before performing the update operation
if($nicksname != $current_user->nickname){
    wp_update_user( array ( 'ID' => $user_id, 'nickname' => $nicksname ) ) ;
}
return $tableuserinf;
| improve this answer | |
  • I get it working, but the form value is not immediately changed when the database was updated successfully. – Ari Sep 21 '13 at 14:49

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