wordpress注册用户第一次登录必须修改密码,如何实现这个修改密码的功能呢?
首先,新建一个表单页面
<!-- 更改密码 --> <article class="change-password-content"> <div class = "change-password-messages"> <p>您必须更改密码,才能继续访问网站内容</p> </div> <div class = "change-password-form"> <label for="password">新密码></label><br /> <input type="password" class="form-control password1" /> <label for="password2">重复密码</label><br /> <input type="password" class="form-control password2" /> <input type="submit" name="change-password" value="提交修改" class="btn-change-pass" /> </div> </article> <script> $(document).ready(function() { // admin-ajax var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>'; function cvf_form_validate(element) { element.effect("highlight", { color: "#F2DEDE" }, 1500); element.parent().effect('shake'); } // 表单按钮 $('body').on('click', '.btn-change-pass', function(e) { // 验证空字段或不匹配的密码 if ($('.change-password-form .password1').val() === '') { cvf_form_validate($('.password1')); } else if ($('.change-password-form .password2').val() === '') { cvf_form_validate($('.password2')); } else if ($('.change-password-form .password2').val() !== $('.change-password-form .password1').val()) { $(".change-password-messages").html('<p class = "bg-danger"><span class = "glyphicon glyphicon-remove-circle"></span> 密码不匹配</p>'); } else { // 自定义加载GIF图像 $(".change-password-messages").html('<p><img src = "<?php bloginfo('template_url'); ?>/images/loading.gif" class = "loader" /></p>'); // 定义Ajax参数 var data = { 'action': 'wpsite_change_password', 'lb_action': 'change_password', 'new_password': $('.change-password-form .password2').val() }; $.post(ajaxurl, data, function(response) { //检测收到的Ajax响应,然后为每个特定的响应做必要的逻辑 if(response === 'success') { $(".change-password-messages").html('<p class = "bg-success">密码修改成功 <br /><a href = "<?php echo home_url(); ?>">点击这里继续</a></p>'); $('.change-password-form').hide(); } else if (response === 'error') { $(".change-password-messages").html('<p class = "bg-danger"><span class = "glyphicon glyphicon-remove-circle"></span> 密码修改失败</p>'); $('.change-password-form').show(); } }); } }); }); </script>
ajax交互,在functions文件中处理逻辑
<?php add_action('wp_ajax_wpsite_change_password', array('wpsite_change_password', 'lb_change_password') ); add_action('wp_ajax_nopriv_wpsite_change_password', array('wpsite_change_password', 'lb_change_password') ); function wpsite_change_password() { global $current_user; if(isset($_POST['lb_action']) && $_POST['lb_action'] == 'change_password') { $password = sanitize_text_field($_POST['new_password']); // 定义将传递给 wp_update_user() $userdata = array( 'ID' => $current_user->ID, 'user_pass' => $password ); $user_id = wp_update_user($userdata); // 检查返回的字符串是否等于当前的用户ID if($user_id == $current_user->ID){ update_user_meta($current_user->ID, 'wpsite_changepass_status', 1); echo 'success'; } else { echo 'error'; } } // 始终退出,以避免进重复操作 exit(); } ?>
然后必须在用户登录以后的界面添加如下逻辑
至此,wordpress注册用户第一次登录必须修改密码功能就完成了!