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

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

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

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

创建一个页面模板

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

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

创建表单

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

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

&lt;?php the_content(); ?&gt;

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

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

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

表单数据验证和错误处理

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

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

&lt;?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(&quot;^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$&quot;, 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 = &quot;Name: $name \n\nEmail: $email \n\nComments: $comments&quot;;
        $headers = 'From: '.$name.' &lt;'.$emailTo.'&gt;' . &quot;\r\n&quot; . 'Reply-To: ' . $email;
 
        mail($emailTo, $subject, $body, $headers);
        $emailSent = true;
    }
 
} ?&gt;

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

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

&lt;?php
/*
Template Name: Contact
*/
?&gt;
 
&lt;?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(&quot;^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$&quot;, 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 = &quot;Name: $name \n\nEmail: $email \n\nComments: $comments&quot;;
        $headers = 'From: '.$name.' &lt;'.$emailTo.'&gt;' . &quot;\r\n&quot; . 'Reply-To: ' . $email;
 
        mail($emailTo, $subject, $body, $headers);
        $emailSent = true;
    }
 
} ?&gt;
&lt;?php get_header(); ?&gt;
    &lt;div id=&quot;container&quot;&gt;
        &lt;div id=&quot;content&quot;&gt;
 
            &lt;?php if (have_posts()) : while (have_posts()) : the_post(); ?&gt;
            &lt;div &lt;?php post_class() ?&gt; id=&quot;post-&lt;?php the_ID(); ?&gt;&quot;&gt;
                &lt;h1 class=&quot;entry-title&quot;&gt;&lt;?php the_title(); ?&gt;&lt;/h1&gt;
                    &lt;div class=&quot;entry-content&quot;&gt;
                        &lt;?php if(isset($emailSent) &amp;&amp; $emailSent == true) { ?&gt;
                            &lt;div class=&quot;thanks&quot;&gt;
                                &lt;p&gt;Thanks, your email was sent successfully.&lt;/p&gt;
                            &lt;/div&gt;
                        &lt;?php } else { ?&gt;
                            &lt;?php the_content(); ?&gt;
                            &lt;?php if(isset($hasError) || isset($captchaError)) { ?&gt;
                                &lt;p class=&quot;error&quot;&gt;Sorry, an error occured.&lt;p&gt;
                            &lt;?php } ?&gt;
 
                        &lt;form action=&quot;&lt;?php the_permalink(); ?&gt;&quot; id=&quot;contactForm&quot; method=&quot;post&quot;&gt;
                            &lt;ul class=&quot;contactform&quot;&gt;
                            &lt;li&gt;
                                &lt;label for=&quot;contactName&quot;&gt;Name:&lt;/label&gt;
                                &lt;input type=&quot;text&quot; name=&quot;contactName&quot; id=&quot;contactName&quot; value=&quot;&lt;?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?&gt;&quot; class=&quot;required requiredField&quot; /&gt;
                                &lt;?php if($nameError != '') { ?&gt;
                                    &lt;span class=&quot;error&quot;&gt;&lt;?=$nameError;?&gt;&lt;/span&gt;
                                &lt;?php } ?&gt;
                            &lt;/li&gt;
 
                            &lt;li&gt;
                                &lt;label for=&quot;email&quot;&gt;Email&lt;/label&gt;
                                &lt;input type=&quot;text&quot; name=&quot;email&quot; id=&quot;email&quot; value=&quot;&lt;?php if(isset($_POST['email']))  echo $_POST['email'];?&gt;&quot; class=&quot;required requiredField email&quot; /&gt;
                                &lt;?php if($emailError != '') { ?&gt;
                                    &lt;span class=&quot;error&quot;&gt;&lt;?=$emailError;?&gt;&lt;/span&gt;
                                &lt;?php } ?&gt;
                            &lt;/li&gt;
 
                            &lt;li&gt;&lt;label for=&quot;commentsText&quot;&gt;Message:&lt;/label&gt;
                                &lt;textarea name=&quot;comments&quot; id=&quot;commentsText&quot; rows=&quot;20&quot; cols=&quot;30&quot; class=&quot;required requiredField&quot;&gt;&lt;?php if(isset($_POST['comments'])) { if(function_exists('stripslashes')) { echo stripslashes($_POST['comments']); } else { echo $_POST['comments']; } } ?&gt;&lt;/textarea&gt;
                                &lt;?php if($commentError != '') { ?&gt;
                                    &lt;span class=&quot;error&quot;&gt;&lt;?=$commentError;?&gt;&lt;/span&gt;
                                &lt;?php } ?&gt;
                            &lt;/li&gt;
 
                            &lt;li&gt;
                                &lt;input type=&quot;submit&quot;&gt;Send email&lt;/input&gt;
                            &lt;/li&gt;
                        &lt;/ul&gt;
                        &lt;input type=&quot;hidden&quot; name=&quot;submitted&quot; id=&quot;submitted&quot; value=&quot;true&quot; /&gt;
                    &lt;/form&gt;
                &lt;?php } ?&gt;
                &lt;/div&gt;&lt;!-- .entry-content --&gt;
            &lt;/div&gt;&lt;!-- .post --&gt;
 
                &lt;?php endwhile; endif; ?&gt;
        &lt;/div&gt;&lt;!-- #content --&gt;
    &lt;/div&gt;&lt;!-- #container --&gt;
 
&lt;?php get_sidebar(); ?&gt;
&lt;?php get_footer(); ?&gt;

添加jQuery表单验证功能

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

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

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

&lt;?php if( is_page('contact') ){ ?&gt;
    &lt;script type=&quot;text/javascript&quot; src=&quot;&lt;?php bloginfo('template_directory'); ?&gt;/js/jquery.validate.min.js&quot;&gt;&lt;/script&gt;
    &lt;script type=&quot;text/javascript&quot; src=&quot;&lt;?php bloginfo('template_directory'); ?&gt;/js/verif.js&quot;&gt;&lt;/script&gt;
&lt;?php }?&gt;

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

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

参考资料:catswhocode

中文整理自:SayBlog.Me

来源:

https://www.wpdaxue.com/add-contact-form-for-wordpress-theme.html

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_33254.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?