为你的 WordPress 主题创建内置的联系表单

本文目录[隐藏]1创建一个页面模板2创建表单3表单数据验证和错误处理4添加jQuery表单验证功能

有许多WordPress插件都可以为你的博客添加一个联系表单,但是似乎并没有这个必要,因为,在今天的这个教程中,我将向大家介绍一个不用插件就能为你的WordPress主题创建一个内置式联系表单的方法,并为表单加上一个jQuery的验证功能,简单,易用,可靠。

一个内置联系表单形如下图所示,十分简单:

add-contact-form-for-wordpress-theme-wpdaxue_com

创建一个页面模板

将主题中page.php 文件里的代码复制到一个新文件,并将这个新文件命名为contact.php,然后在此文件的开头加上这样的一段注释(你可以从WordPress后台新建一个叫"Contact"的页面):

1
2
3
4
5
<?php
/*
Template Name: Contact
*/
?>

<?php
/*
Template Name: Contact
*/
?>

之后这个contact.php文件看起来应该象这样:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?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() ?>

<?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() ?>

创建表单

现在,我们需要建立一个简单的表单了,只需将下面的代码复制并粘贴到<div class="entry-content">……</div>这对标签之间:

注:如果你的页面结构不一样,可以找到

1
<?php the_content(); ?>

<?php the_content(); ?>

将下面的代码复制并粘贴到它的下面,这样就可以了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<form action="<?php the_permalink(); ?>" id="contactForm" method="post">
    <ul>
        <li>
            <label for="contactName">姓名:</label>
            <input type="text" name="contactName" id="contactName" value="" />
        </li>
        <li>
            <label for="email">邮箱:</label>
            <input type="text" name="email" id="email" value="" />
        </li>
        <li>
            <label for="commentsText">邮件内容:</label>
            <textarea name="comments" id="commentsText" rows="20" cols="30"></textarea>
        </li>
        <li>
            <button type="submit">发送邮件</button>
        </li>
    </ul>
    <input type="hidden" name="submitted" id="submitted" value="true" />

<form action="<?php the_permalink(); ?>" id="contactForm" method="post">
<ul>
<li>
<label for="contactName">姓名:</label>
<input type="text" name="contactName" id="contactName" value="" />
</li>
<li>
<label for="email">邮箱:</label>
<input type="text" name="email" id="email" value="" />
</li>
<li>
<label for="commentsText">邮件内容:</label>
<textarea name="comments" id="commentsText" rows="20" cols="30"></textarea>
</li>
<li>
<button type="submit">发送邮件</button>
</li>
</ul>
<input type="hidden" name="submitted" id="submitted" value="true" />

代码看起来十分简单,也不用再作多余解释了。注意一下,上面最后一行inputtype值是”hidden” ,稍后用于检验表单是否已经提交。

表单数据验证和错误处理

到此,这个表单看起来已经很帅了,但还不能使用,因为还没有发送任何邮件,所以我们需要做的就是要验证一下表单提交及其所填内容是否正确。

我们需要作如下判断:如果表单填写正确,则获取管理员邮箱地址并发送内容;如果表单填写有误,则提示错误。将下面的代码粘贴到模板声明和get_header()函数的中间:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<?php
if(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: ' . $email;
 
        mail($emailTo, $subject, $body, $headers);
        $emailSent = true;
    }
 
} ?>

<?php
if(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: ‘ . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
} ?>

我们这样做的目的是为了确保表单已经提交并且填写正确,如果存在错误,如表单留空或者邮件地址不正确等,就会返回错误信息,表单提交发送失败。

现在,我们需要在相关表单区域设置显示错误信息,比如在姓名一栏的下方显示“请输入你的邮箱地址”等,以下是整个表单contact.php模板的代码结构:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
<?php
/*
Template Name: Contact
*/
?>
 
<?php
if(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: ' . $email;
 
        mail($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 endwhile; endif; ?>
        </div><!-- #content -->
    </div><!-- #container -->
 
<?php get_sidebar(); ?>
<?php get_footer(); ?>

<?php
/*
Template Name: Contact
*/
?>
<?php
if(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: ‘ . $email;
mail($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 endwhile; endif; ?>
</div><!– #content –>
</div><!– #container –>
<?php get_sidebar(); ?>
<?php get_footer(); ?>

添加jQuery表单验证功能

其实我们制作的这个表单到此已经可以正常使用了,但是我们可以在验证功能上进一步加强,添加jQuery用户端验证过程,配合一个插件validate jQuery plugin,此插件很不错,对于表单验证快速准确而且简单,我们可以到这里下载jQuery validate plugin,将插件上传到我们主题的/js目录下,然后再将下面这一段代码粘贴进一个新文件中,保存文件名为 verif.js

1
2
3
$(document).ready(function(){
    $("#contactForm").validate();
});

$(document).ready(function(){
$("#contactForm").validate();
});

现在,我们必须将这个javascript文件跟我们的主题连接起来,打开 header.php文件,将下面的代码粘贴在<head> 和 </head> 这对标签的中间:

1
2
3
4
<?php if( is_page('contact') ){ ?>
    <script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/js/jquery.validate.min.js"></script>
    <script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/js/verif.js"></script>
<?php }?>

<?php if( is_page(‘contact’) ){ ?>
<script type="text/javascript" src="<?php bloginfo(‘template_directory’); ?>/js/jquery.validate.min.js"></script>
<script type="text/javascript" src="<?php bloginfo(‘template_directory’); ?>/js/verif.js"></script>
<?php }?>

这样做之后,保存一下文件,完工!

然后,你只需要发布一个新页面,然后选择 Contact  模板即可。

参考资料:catswhocode

中文整理自:SayBlog.Me

本人擅长Ai、Fw、Fl、Br、Ae、Pr、Id、Ps等软件的安装与卸载,精通CSS、JavaScript、PHP、ASP、C、C++、C#、Java、Ruby、Perl、Lisp、Python、Objective-C、ActionScript、Pascal等单词的拼写,熟悉Windows、Linux、OS X、Android、iOS、WP8等系统的开关机。

通过下面的方式来联系我们:

电邮:138762189@qq.com

联系QQ:点击这里给我发消息

官方站:www.tadke.com

※ ※ 联系请加我的企鹅号 ※※

※ ※技术支持请微信联系站长 ※※

Copyright © 2023 Tadke.com. 琼ICP备20000547号