如何利用WordPress创建自定义注册表单插件

如何利用WordPress创建自定义注册表单插件,第1张

WordPress默认的注册表单仅由两个字段组成—-用户名和邮箱。

这个仅有的用户名和邮箱表单字段使得注册速度非常的简单。首先,你输入一个用户名,然后输入邮箱,这个邮箱就是用来接收密码的。接下来,你使用邮箱接收到的密码登陆站点,并且完成个人资料,把密码修改成简单易记得。

仅仅是在站点注册,而不是让用户区经历这些压力,那为什么除了用户名和邮箱之外,不提供一个直接的、包含一些额外重要的表单字段,例如密码、个人的URL、个人简介、昵称和他们的姓名的注册表单供用户使用呢?

这对于像Tuts+的多用户网站是非常有用的。

在这篇文章中,我们将使用下列的表单字段建立一个自定义的表单注册插件:

username

password

email

website URL

first name

last name

nickname

biography (or an about section)

这个自定义表单插件可以通过使用短代码和联系模板整合到WordPress中。

利用短代码模板,你可以在你的站点中创建一个正式的注册页面。你也可以再一篇发表的文章中是用短代码模板,这样用户就可以在阅读完你的文章之后进行注册。

如果你想添加一个注册表单在你网站侧边栏的某个具体位置,你可以对WordPress主题中仅仅期望放置标签模板的位置进行编辑,来创建需要的注册表单。

在创建之前,需要注意的是,用户名、密码和电子邮件字段是必需的。

当我们编写验证函数时,我们将强制执行这些规则。

构建插件

正如说的那样,我们开始对插件编码。首先,包含插件的头部:

<?php

/*

Plugin Name: Custom Registration

Plugin URI: http://code.tutsplus.com

Description: Updates user rating based on number of posts.

Version: 1.0

Author: Agbonghama Collins

Author URI: http://tech4sky.com

*/

接下来,我们创建一个包含注册表单的HTML代码的PHP函数:

function registration_form( $username, $password, $email, $website, $first_name, $last_name, $nickname, $bio ) {

echo '

<style>

div {

margin-bottom:2px

}

input{

margin-bottom:4px

}

</style>

'

echo '

<form action="' . $_SERVER['REQUEST_URI'] . '" method="post">

<div>

<label for="username">Username <strong>*</strong></label>

<input type="text" name="username" value="' . ( isset( $_POST['username'] ) ? $username : null ) . '">

</div>

<div>

<label for="password">Password <strong>*</strong></label>

<input type="password" name="password" value="' . ( isset( $_POST['password'] ) ? $password : null ) . '">

</div>

<div>

<label for="email">Email <strong>*</strong></label>

<input type="text" name="email" value="' . ( isset( $_POST['email']) ? $email : null ) . '">

</div>

<div>

<label for="website">Website</label>

<input type="text" name="website" value="' . ( isset( $_POST['website']) ? $website : null ) . '">

</div>

<div>

<label for="firstname">First Name</label>

<input type="text" name="fname" value="' . ( isset( $_POST['fname']) ? $first_name : null ) . '">

</div>

<div>

<label for="website">Last Name</label>

<input type="text" name="lname" value="' . ( isset( $_POST['lname']) ? $last_name : null ) . '">

</div>

<div>

<label for="nickname">Nickname</label>

<input type="text" name="nickname" value="' . ( isset( $_POST['nickname']) ? $nickname : null ) . '">

</div>

<div>

<label for="bio">About / Bio</label>

<textarea name="bio">' . ( isset( $_POST['bio']) ? $bio : null ) . '</textarea>

</div>

<input type="submit" name="submit" value="Register"/>

</form>

'

}

请注意注册字段是作为变量传递给上面的函数。在函数中,你会看到下面代码的示例:

( isset( $_POST['lname'] ) ? $last_name : null )

这个三元 *** 作符是检查全局变量数组$_POST是否包含数据,如果有数据,就把填充的表单字段值保存以便进入下一个字段。

除非你验证了表单数据并且清空了表单数据,一个注册表单才能算完成,否则就不算。因此,我们要创建一个名为 registration_validation的表单验证函数。

为了简化验证的”痛苦”,我们可以使用WordPress中的 WP_Error 类。跟着我编写验证函数:

1、创建函数,并将注册表单的字段值作为函数的参数传递进来

function registration_validation( $username, $password, $email, $website, $first_name, $last_name, $nickname, $bio ) {

2、实例化 WP_Error 类,并把实例作为全局变量,以便于我们可以再函数的作用域之外使用。

global $reg_errors

$reg_errors = new WP_Error

3、记住:我们说的用户名、密码和电子邮件是必填的,不要忽略了。为了执行这个规则,我们需要检查它们中任何一个是否为空。如果为空,我们就将错误信息追加给WP_Error 类的实例。

if ( empty( $username ) || empty( $password ) || empty( $email ) ) {

$reg_errors->add('field', 'Required form field is missing')

}

4、我们也可以确保用户名的字符个数不小于4

if ( 4 >strlen( $username ) ) {

$reg_errors->add( 'username_length', 'Username too short. At least 4 characters is required' )

}

5、检查用户名是否被注册了

if ( username_exists( $username ) )

$reg_errors->add('user_name', 'Sorry, that username already exists!')

6、利用WordPress的 validate_username 函数确保用户名是可用的

if ( ! validate_username( $username ) ) {

$reg_errors->add( 'username_invalid', 'Sorry, the username you entered is not valid' )

}

7、确保用户输入的密码的字符个数不小于5

if ( 5 >strlen( $password ) ) {

$reg_errors->add( 'password', 'Password length must be greater than 5' )

}

8、检查电子邮件是否有效

if ( !is_email( $email ) ) {

$reg_errors->add( 'email_invalid', 'Email is not valid' )

}

9、检查电子邮件是否被注册

if ( !is_email( $email ) ) {

$reg_errors->add( 'email_invalid', 'Email is not valid' )

}

10.、如果用户填写了网站字段,需要检查其是否有效

if ( ! empty( $website ) ) {

if ( ! filter_var( $website, FILTER_VALIDATE_URL ) ) {

$reg_errors->add( 'website', 'Website is not a valid URL' )

}

}

11、最后,我们在WP_Error实例中对错误进行循环,并显示个别的错误

if ( is_wp_error( $reg_errors ) ) {

foreach ( $reg_errors->get_error_messages() as $error ) {

echo '<div>'

echo '<strong>ERROR</strong>:'

echo $error . '<br/>'

echo '</div>'

}

}

这样,验证函数就完成了。接下来是 complete_registration()函数,用于处理用户注册。用户的注册真正完成是通过wp_insert_user函数,

用户的数据作为数据保存后可以作为此函数的参数。

function complete_registration() {

global $reg_errors, $username, $password, $email, $website, $first_name, $last_name, $nickname, $bio

if ( 1 >count( $reg_errors->get_error_messages() ) ) {

$userdata = array(

'user_login' => $username,

'user_email' => $email,

'user_pass' => $password,

'user_url' => $website,

'first_name' => $first_name,

'last_name' => $last_name,

'nickname' => $nickname,

'description' => $bio,

)

$user = wp_insert_user( $userdata )

echo 'Registration complete. Goto <a href="' . get_site_url() . '/wp-login.php">login page</a>.'

}

}

在上面的函数中,我们将$reg_errors作为WP_Error的实例,并将表单字段作为全局变量以便于可以再全局作用域中使用。

我们需要检查$reg_errors是否包含任何错误,如果没有错误,则将用户注册信息插入到WordPress的数据库并用登陆链接来显示注册完成的信息。

然后,把所有我们之前创建的函数全部放在全局函数custom_registration_function()之中

function custom_registration_function() {

if ( isset($_POST['submit'] ) ) {

registration_validation(

$_POST['username'],

$_POST['password'],

$_POST['email'],

$_POST['website'],

$_POST['fname'],

$_POST['lname'],

$_POST['nickname'],

$_POST['bio']

)

// sanitize user form input

global $username, $password, $email, $website, $first_name, $last_name, $nickname, $bio

$username = sanitize_user( $_POST['username'] )

$password = esc_attr( $_POST['password'] )

$email = sanitize_email( $_POST['email'] )

$website= esc_url( $_POST['website'] )

$first_name = sanitize_text_field( $_POST['fname'] )

$last_name = sanitize_text_field( $_POST['lname'] )

$nickname = sanitize_text_field( $_POST['nickname'] )

$bio = esc_textarea( $_POST['bio'] )

// call @function complete_registration to create the user

// only when no WP_error is found

complete_registration(

$username,

$password,

$email,

$website,

$first_name,

$last_name,

$nickname,

$bio

)

}

registration_form(

$username,

$password,

$email,

$website,

$first_name,

$last_name,

$nickname,

$bio

)

}

我需要说明一下全局函数 custom_registration_function()中有哪些代码。

首先,我通过检查$_POST['submit']是否是空来确定表单是否提交。如果提交了,我就调用

registration_validation()函数来验证用户提交的表单.

然后,确保表单数据的有效性并将有效的数据在表单字段域之后用一个变量命名。最后,调用

complete_registration()函数保存用户。我需要调用registration_form()函数来显示用户注册表单。

我之前提到过,我打算用短代码模板来支持注册插件。下面就是短代码模的支持代码:

// Register a new shortcode: [cr_custom_registration]

add_shortcode( 'cr_custom_registration', 'custom_registration_shortcode' )

// The callback function that will replace [book]

function custom_registration_shortcode() {

ob_start()

custom_registration_function()

return ob_get_clean()

}

到这里为止,我们已经完成了插件,下面的一张图片展示了注册表单的外观。

注意,你可能不会得到完全相同的外观,因为WordPress站点的CSS样式不同。

应用插件

为了在WordPress的文章页或独立页面使用这个插件,可以加入以下代码:[cr_custom_registration]

也可以添加列出的模板标记<?php custom_registration_function()?>.,这样可以让表单插件成

为WordPress主题的一个部分。你可以从这篇文章的附加代码得到这个插件。

总结

在这篇文章中,我们一步步创建了一个自定义注册表单并添加到WordPress站点。你可以添加额外字段,进一

步扩展这个注册表单,例如用户角色,AOL IM 账户,但是确保数据时有效的。

当然第一步是要创建一个页面模板。先创建一个 page-contact.php的文件,然后将page.php文件里的代码复制到这个新建的文件里。为了确保WordPress能够将它当作一个页面模板来看待,我们需要在contact.php文件的开头添加下面的注释<?php/*Template Name: Contact*/?>也就是说contact.php文件应该是下面这样子的:<?php/*Template Name: Contact*/?><?php get_header() ?><div id="container"><div id="content"><?php the_post() ?><div id="post-<?php the_ID() ?>" class="post"><div class="entry-content"></div><!-- .entry-content -></div><!-- .post--></div><!-- #content --></div><!-- #container --><?php get_sidebar() ?><?php get_footer() ?>步骤二: 创建表单现在,我们需要创建一个简单的联系表单,只要将下面的代码粘贴到 entry-content div内部即可。<form action="<?php the_permalink()?>" id="contactForm" method="post"><ul><li><label for="contactName">Name:</label><input type="text" name="contactName" id="contactName" value="" /></li><li><label for="email">Email</label><input type="text" name="email" id="email" value="" /></li><li><label for="commentsText">Message:</label><textarea name="comments" id="commentsText" rows="20" cols="30"></textarea></li><li><button type="submit">Send email</button></li></ul><input type="hidden" name="submitted" id="submitted" value="true" /></form>这个html代码相当明了,不过要注意下第19行的 input type=”hidden”,我们后面会用它来检查表单是否提交。步骤三: 数据的处理和错误的应对表单看起来已经不错了,但是此刻它仍然是无效的因为它没有发送任何邮件。我们需要做的是验证表单是否提交,然后再验证表单的字段填写是否正确。如果填写都是正确的,就会收到博客管理员的邮件并向他们发送邮件。否则,就无法发送邮件,错误提示就会显示给用户。将下面的代码粘贴在页面模板声明和get_header()函数之间:<?phpif(isset($_POST['submitted'])) {if(trim($_POST['contactName']) === '') {$nameError = 'Please enter your name.'$hasError = true} else {$name = trim($_POST['contactName'])}if(trim($_POST['email']) === '') {$emailError = 'Please enter your email address.'$hasError = true} else if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {$emailError = 'You entered an invalid email address.'$hasError = true} else {$email = trim($_POST['email'])}if(trim($_POST['comments']) === '') {$commentError = 'Please enter a message.'$hasError = true} else {if(function_exists('stripslashes')) {$comments = stripslashes(trim($_POST['comments']))} else {$comments = trim($_POST['comments'])}}if(!isset($hasError)) {$emailTo = get_option('tz_email')if (!isset($emailTo) || ($emailTo == '') ){$emailTo = get_option('admin_email')}$subject = '[PHP Snippets] From '.$name$body = "Name: $name \n\nEmail: $email \n\nComments: $comments"$headers = 'From: '.$name.' <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $emailmail($emailTo, $subject, $body, $headers)$emailSent = true}} ?>这段代码确认表单是否提交,是否正确填写。如果发生错误,比如,一个字段是空的,或者邮箱地址不正确,就会返回错误提示的信息,表单就无法提交。接着就是显示错误提示的信息,例如,“请输入你的姓名”。 下面是完整的表单页面模板,如果喜欢的话你可以原封不动地使用。<?php/*Template Name: Contact*/?><?phpif(isset($_POST['submitted'])) {if(trim($_POST['contactName']) === '') {$nameError = 'Please enter your name.'$hasError = true} else {$name = trim($_POST['contactName'])}if(trim($_POST['email']) === '') {$emailError = 'Please enter your email address.'$hasError = true} else if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {$emailError = 'You entered an invalid email address.'$hasError = true} else {$email = trim($_POST['email'])}if(trim($_POST['comments']) === '') {$commentError = 'Please enter a message.'$hasError = true} else {if(function_exists('stripslashes')) {$comments = stripslashes(trim($_POST['comments']))} else {$comments = trim($_POST['comments'])}}if(!isset($hasError)) {$emailTo = get_option('tz_email')if (!isset($emailTo) || ($emailTo == '') ){$emailTo = get_option('admin_email')}$subject = '[PHP Snippets] From '.$name$body = "Name: $name \n\nEmail: $email \n\nComments: $comments"$headers = 'From: '.$name.' <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $emailmail($emailTo, $subject, $body, $headers)$emailSent = true}} ?><?php get_header()?><div id="container"><div id="content"><?php if (have_posts()) : while (have_posts()) : the_post()?><div <?php post_class() ?>id="post-<?php the_ID()?>"><h1 class="entry-title"><?php the_title()?></h1><div class="entry-content"><?php if(isset($emailSent) &&$emailSent == true) { ?><div class="thanks"><p>Thanks, your email was sent successfully.</p></div><?php } else { ?><?php the_content()?><?php if(isset($hasError) || isset($captchaError)) { ?><p class="error">Sorry, an error occured.<p><?php } ?><form action="<?php the_permalink()?>" id="contactForm" method="post"><ul class="contactform"><li><label for="contactName">Name:</label><input type="text" name="contactName" id="contactName" value="<?php if(isset($_POST['contactName'])) echo $_POST['contactName']?>" class="required requiredField" /><?php if($nameError != '') { ?><span class="error"><?=$nameError?></span><?php } ?></li><li><label for="email">Email</label><input type="text" name="email" id="email" value="<?php if(isset($_POST['email'])) echo $_POST['email']?>" class="required requiredField email" /><?php if($emailError != '') { ?><span class="error"><?=$emailError?></span><?php } ?></li><li><label for="commentsText">Message:</label><textarea name="comments" id="commentsText" rows="20" cols="30" class="required requiredField"><?php if(isset($_POST['comments'])) { if(function_exists('stripslashes')) { echo stripslashes($_POST['comments'])} else { echo $_POST['comments']} } ?></textarea><?php if($commentError != '') { ?><span class="error"><?=$commentError?></span><?php } ?></li><li><input type="submit">Send email</input></li></ul><input type="hidden" name="submitted" id="submitted" value="true" /></form><?php } ?></div><!-- .entry-content --></div><!-- .post --><?php endwhileendif?></div><!-- #content --></div><!-- #container --><?php get_sidebar()?><?php get_footer()?>第四步骤: 添加jQuery验证到此为止,我们的表达已经能够非常完美的运作了。不过你还可以通过添加一个客户端验证来改善它。为此,我打算使用jQuery和 validate jQuery插件,这个插件非常强大,通过它你可以正确、快速、轻松地验证表单。首先是下载验证插件 然后将它上传到你的主题文件里,完成之后,将下面的代码粘贴到一个新的文件里:$(document).ready(function(){$("#contactForm").validate()})将这个文件命名为verif.js并保存至你的主题文件目录里。现在就需要将这个javascript文件链接到主题里,打开你的header.php文件,把下面的代码粘贴到<head>和</head>这两个标签之间:<?php if( is_page('contact') ){ ?>


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/bake/11255803.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-14
下一篇 2023-05-14

发表评论

登录后才能评论

评论列表(0条)

保存