Skip to main content
1 of 4
Kirkland
  • 298
  • 2
  • 3
  • 14

How to use wp_set_password in a plugin?

I am developing a private plugin for my multisite installation. I want the user to be able to update their WP password from the plugin settings page. I've tried every example I can find without luck.

The code below is one of many failed attempts. In this one do_things is never called. In versions where I do successfully call wp_set_password I get the "Headers already sent" error and the user is auto-logged out.

Any help would be greatly appreciated.

<?php
/*
  Plugin Name: My Plugin
  Description:
  Author: Kirkland
  Version: 1.0.0
*/
class My_New_Plugin
{
  public function __construct()
  {
    add_action('admin_menu', array($this, 'create_plugin_settings_page'));
    add_action('send_headers', array($this, 'do_things'));
  }

  public function create_plugin_settings_page()
  {
    add_submenu_page('index.php', 'My Plugin', 'My Plugin', 'read', 'my_plugin', array($this, 'plugin_settings_page_content'), 2);
  }

  public function do_things() {
    wp_set_password('test', get_current_user_id());

    $user = wp_signon(array(
      'user_login' => 'deleteme',
      'user_password' => 'test',
      'remember' => true
    ), false);

    if (is_wp_error($user)) {
      echo $user->get_error_message();
    } else {
      wp_clear_auth_cookie();
      do_action('wp_login', $user->ID);
      wp_set_current_user($user->ID);
      wp_set_auth_cookie($user->ID, true);
      $redirect_to = $_SERVER['REQUEST_URI'];
      wp_safe_redirect($redirect_to);
      exit;
    }
  }

  public function plugin_settings_page_content()
  {
    echo '<div>stuff</div>';
  }
}
new My_New_Plugin();
Kirkland
  • 298
  • 2
  • 3
  • 14