为WordPress添加前台AJAX注册登录功能

功能前台化已成为WordPress主题制作的一大趋势,抛却缓慢臃肿的后台不说,前台便捷操作能给用户带来良好体验。登录与注册是网站的重要功能之一,这篇文章将讲述如何实现漂亮的WordPress前台登录注册功能,此外观移植自觉唯主题。

ajax-login-register

简要说明

此功能的实现是由AJAX提交表格数据代替PHP submit提交至WordPress自带的admin-ajax.php,再进行wordpress内部的php验证处理,基于功能简化要求,使用了jquery表单验证库,在输入界面就提醒用户的明显错误,如邮箱格式不正确等等。

必须文件

以上文件必须引入,请下载jQuery Validation Plugin 表单验证修改版,下载地址见文章末尾

界面实现

首先使用php和css组织基本界面。

php代码如下:

点击登录或注册弹窗锚点

弹窗代码

切换注册

登录

切换登录

注册

此php代码请放到要显示登录按钮的地方,比如导航条。

CSS样式代码如下:

/* Login pop
/* ----------- */
.fadeIn #sign{opacity:1;-webkit-transform:translate3d(0,0,0);-moz-transform:translate3d(0,0,0);-o-transform:translate3d(0,0,0);transform:translate3d(0,0,0)}
#sign,#sign a{font-size:12px !important;line-height:1.5;}
#sign{position:fixed;z-index:9999;top:80px;left:50%;width:400px;margin-left:-200px;opacity:0;-webkit-transform:translate3d(0,-600px,0);-moz-transform:translate3d(0,-600px,0);-o-transform:translate3d(0,-600px,0);transform:translate3d(0,-600px,0);min-height:200px;-webkit-transition:all .3s ease-out;-moz-transition:all .3s ease-out;-o-transition:all .3s ease-out;transition:all .3s ease-out;-webkit-perspective:800px;-moz-perspective:800px;-ms-perspective:800px;perspective:800px}
#sign .part{position:absolute;width:100%;left:0;top:0;background-color:#FFF;padding:50px 50px 40px 50px;box-sizing:border-box;-webkit-transform-style:preserve-3d;-moz-transform-style:preserve-3d;-ms-transform-style:preserve-3d;transform-style:preserve-3d;-webkit-transition:all .9s ease-in-out;-moz-transition:all .9s ease-in-out;-ms-transition:all .9s ease-in-out;transition:all .9s ease-in-out;-webkit-backface-visibility:hidden;-moz-backface-visibility:hidden;-ms-backface-visibility:hidden;backface-visibility:hidden;display:none}
#sign.sign .part.loginPart{-webkit-transform:rotateY(0deg);-moz-transform:rotateY(0deg);-ms-transform:rotateY(0deg);transform:rotateY(0deg);z-index:1;display:block}
#sign.sign .part.registerPart{-webkit-transform:rotateY(-180deg);-moz-transform:rotateY(-180deg);-ms-transform:rotateY(-180deg);transform:rotateY(-180deg);z-index:0;display:block}
#sign.register .part.loginPart{-webkit-transform:rotateY(180deg);-moz-transform:rotateY(180deg);-ms-transform:rotateY(180deg);transform:rotateY(180deg);z-index:0;display:block}
#sign.register .part.registerPart{-webkit-transform:rotateY(0deg);-moz-transform:rotateY(0deg);-ms-transform:rotateY(0deg);transform:rotateY(0deg);z-index:1;display:block}
#sign form h3{font-size:18px;margin-bottom:20px}
#sign form h3 p{font-size:12px;color:#999;margin:0 0 0 10px;display:inline-block}
#sign form .status .error{color:#ea4c89}
#sign form .status .success{color:#00c3b6}
#sign form p{margin:10px auto;position:relative}
#sign form label.error{color:#FFF;background-color:#7656E8;padding:0 4px;position:absolute;z-index:5;right:10px;top:11px}
#sign form label.icon{position:absolute;right:10px;top:5px;color:#999;font-size:20px;color:rgba(0,0,0,.3)}
#sign form label.icon i{width:20px;text-align:center}
#sign form input{border:1px solid #ddd;padding:10px;width:100%;box-sizing:border-box}
#sign ::-webkit-input-placeholder{color:#999}
#sign form input:focus{border:1px solid #00c3b6}
#sign input:-moz-placeholder{color:#999}
#sign input.input-control{padding-right:35px}
#sign form .submit{cursor:pointer;background-color:#00c3b6;color:#FFF;border:0 none;font-size:14px}
#sign form .submit:hover{background-color:#00b5a9}
#sign form .submit:focus{border:0 none}
#sign form .safe{color:#999;margin-top:20px}
#sign form .rememberme{width:inherit;margin-right:3px}
#sign form .lost{float:right}
#sign form .close{position:absolute;right:25px;top:0;width:50px;height:50px;border-radius:0 0 50px 50px;text-align:center;line-height:50px;background-color:#444;font-size:16px;color:#FFF}
#sign form .close i{-webkit-transition:all ease-out .3s;-moz-transition:all ease-out .3s;-o-transition:all ease-out .3s;transition:all ease-out .3s}
#sign form .close:hover i{-webkit-transform:rotate(180deg);-moz-transform:rotate(180deg);-o-transform:rotate(180deg);transform:rotate(180deg)}
#sign .other-sign{border-top:1px solid rgba(0,0,0,.1);margin:30px -50px auto -50px;padding:0 50px}
#sign .other-sign p{margin:20px auto 10px auto}
#sign .other-sign a{display:inline-block;padding:6px 10px;border-radius: 3px;}
#sign .other-sign a i{margin-right:5px}
#sign .other-sign .qqlogin{background-color:#4a9cf8;color:#FFF;}
#sign .other-sign .weibologin {background-color: #e14d4c;color: #FFF;}
#sign .other-sign div{width:150px;text-align:center;float:left;}
#sign .switch{color:#999;cursor:pointer;margin:15px auto;display:inline-block}
#sign .switch i{margin-right:5px;color:#1cbdc5}
.overlay {background: #000;opacity: .8;position: fixed;width: 100%;height: 100%;left: 0;top: 0;z-index: 9998;}
.nav-wrap #login-reg{float: right;margin-left: 5px;font-size: 12px;padding: 14px 0;height: 60px;}
.nav-wrap #login-reg span{display: block;background-color: #757575;background-color: rgba(255,255,255,.2);color: rgba(255,255,255,.8);height: 32px;padding: 0 15px;line-height: 32px;overflow: hidden;display:inline-block;cursor:pointer;float:left;}
#user-login{border-radius: 4px 0 0 4px;}
#user-reg{border-radius: 0 4px 4px 0;margin-left:1px}

css样式可直接放到style.css文件中,

功能实现

ajax提交

ajax提交表单数据代码已经包含在修改版jQuery Validation Plugin 表单验证js文件中,主要是将ajax的提交action指向admin-ajax.php这个wordpress自带ajax处理接口,请直接下载即可。

表单后台处理

先在functions.php文件中添加如下几个函数,代码如下:

/* 获取当前页面url
/* ---------------- */
function tin_get_current_page_url(){
	$ssl = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? true:false;
    $sp = strtolower($_SERVER['SERVER_PROTOCOL']);
    $protocol = substr($sp, 0, strpos($sp, '/')) . (($ssl) ? 's' : '');
    $port  = $_SERVER['SERVER_PORT'];
    $port = ((!$ssl && $port=='80') || ($ssl && $port=='443')) ? '' : ':'.$port;
    $host = isset($_SERVER['HTTP_X_FORWARDED_HOST']) ? $_SERVER['HTTP_X_FORWARDED_HOST'] : isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : $_SERVER['SERVER_NAME'];
    return $protocol . '://' . $host . $port . $_SERVER['REQUEST_URI'];
}

/* AJAX登录变量
/* -------------- */
function ajax_sign_object(){
	$object = array();
	$object[redirecturl] = tin_get_current_page_url();
	$object[ajaxurl] = admin_url( '/admin-ajax.php' );
	$object[loadingmessage] = '正在请求中,请稍等...';
	$object_json = json_encode($object);
	return $object_json;
}

/* AJAX登录验证
/* ------------- */
function tin_ajax_login(){
	$result	= array();
	if(isset($_POST['security']) && wp_verify_nonce( $_POST['security'], 'security_nonce' ) ){
		$creds = array();
		$creds['user_login'] = $_POST['username'];
		$creds['user_password'] = $_POST['password'];
		$creds['remember'] = ( isset( $_POST['remember'] ) ) ? $_POST['remember'] : false;
		$login = wp_signon($creds, false);
		if ( ! is_wp_error( $login ) ){
			$result['loggedin']	= 1;
		}else{
			$result['message']	= ( $login->errors ) ? strip_tags( $login->get_error_message() ) : 'ERROR: ' . esc_html__( '请输入正确用户名和密码以登录', 'tinection' );
		}
	}else{
		$result['message'] = __('安全认证失败,请重试!','tinection');
	}
	header( 'content-type: application/json; charset=utf-8' );
	echo json_encode( $result );
	exit;

}
add_action( 'wp_ajax_ajaxlogin', 'tin_ajax_login' );
add_action( 'wp_ajax_nopriv_ajaxlogin', 'tin_ajax_login' );

/* AJAX注册验证
/* ------------- */
function tin_ajax_register(){
	$result	= array();
	if(isset($_POST['security']) && wp_verify_nonce( $_POST['security'], 'user_security_nonce' ) ){
		$user_login = sanitize_user($_POST['username']);
		$user_pass = $_POST['password'];
		$user_email	= apply_filters( 'user_registration_email', $_POST['email'] );
		$errors	= new WP_Error();
		if( ! validate_username( $user_login ) ){
			$errors->add( 'invalid_username', __( '请输入一个有效用户名','tinection' ) );
		}elseif(username_exists( $user_login )){
			$errors->add( 'username_exists', __( '此用户名已被注册','tinection' ) );
		}elseif(email_exists( $user_email )){
			$errors->add( 'email_exists', __( '此邮箱已被注册','tinection' ) );
		}
		do_action( 'register_post', $user_login, $user_email, $errors );
		$errors = apply_filters( 'registration_errors', $errors, $user_login, $user_email );
		if ( $errors->get_error_code() ){
			$result['success']	= 0;
			$result['message'] 	= $errors->get_error_message();

		} else {
			$user_id = wp_create_user( $user_login, $user_pass, $user_email );
			if ( ! $user_id ) {
				$errors->add( 'registerfail', sprintf( __( '无法注册,请联系管理员','tinection' ), get_option( 'admin_email' ) ) );
				$result['success']	= 0;
				$result['message'] 	= $errors->get_error_message();		
			} else{
				update_user_option( $user_id, 'default_password_nag', true, true ); //Set up the Password change nag.
				wp_new_user_notification( $user_id, $user_pass );	
				$result['success']	= 1;
				$result['message']	= esc_html__( '注册成功','tinection' );
				//自动登录
				wp_set_current_user($user_id);
  				wp_set_auth_cookie($user_id);
  				$result['loggedin']	= 1;
			}

		}	
	}else{
		$result['message'] = __('安全认证失败,请重试!','tinection');
	}
	header( 'content-type: application/json; charset=utf-8' );
	echo json_encode( $result );
	exit;	
}
add_action( 'wp_ajax_ajaxregister', 'tin_ajax_register' );
add_action( 'wp_ajax_nopriv_ajaxregister', 'tin_ajax_register' );

js必须的变量引入

请在主题的header.php或footer.php中引入如下代码:

此代码作用是声明部分js必须的变量,而这些变量是由前面的php函数动态产生的。