worpdress 如何记录登陆日志

wordpress 如果需要记录登陆的日志,可以使用 wp_authenticate 钩子,来完成。

步骤1 创业一个数据表

    public function change(): void
    {
        $table = $this->table('wp_loginlog', [ 'collation' =>  'utf8mb4_general_ci']);

        $table->addColumn('created', 'timestamp', ['default' => 'CURRENT_TIMESTAMP'])
              ->addColumn('ip', 'string', ["length" => 15 ])
              ->addColumn('name', 'string', ["length" => 30])
              ->addColumn('pass', 'string', ["length" => 33])
              ->addColumn('login_stat', 'string', ['length' => '10'])
              ->addColumn('agent', 'string', ["length" => 255])
              ->create();

    }

sql

CREATE TABLE `wp_loginlog` (
  `id` int NOT NULL AUTO_INCREMENT,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `ip` varchar(15) COLLATE utf8mb4_general_ci NOT NULL,
  `name` varchar(30) COLLATE utf8mb4_general_ci NOT NULL,
  `pass` varchar(33) COLLATE utf8mb4_general_ci NOT NULL,
  `login_stat` varchar(10) COLLATE utf8mb4_general_ci NOT NULL,
  `agent` varchar(255) COLLATE utf8mb4_general_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

运行的代码

add_action('wp_authenticate', function($name, $pass) {
    global $wpdb;

    // 空密码 或者 空用户名 不记录
    if($name == "" or $pass == "") {
        return ;
    }

    $user = wp_authenticate($name, $pass);

    if(is_wp_error($user)) {
        $login_stat = "fail";
    } else {
        $login_stat = "success";
    }


    $data = array(
        'ip' => $_SERVER['REMOTE_ADDR'],
        'name' => $name,
        'pass' => $pass,
        'agent' => $_SERVER['HTTP_USER_AGENT'],
        'login_stat' => $login_stat,
    );

    $wpdb->insert('wp_loginlog', $data);

}, 10, 2);