文章题目就很清楚了,这是说一下如何利用JQuery在WordPress上实现contact form的。需要DIY的原因是,虽然WordPress提供了很多contact form的插件,都很强大和多功能,而那些插件大多是通过新建页面插入short code调用联系表单。但是我需要的是能让我插入到模板任意位置(比如现在的index.php中)的contact form代码和一些简单的功能就够了;而且还必需是Ajax刷新的,因为我的主题是标签式浏览,不用Ajax的结果很严重。
表单的功能有几个(实例看本站的contact页面):
- Ajax提交(JQuery实现);
- 自动检测填写内容是否留空或错误邮址(JQuery实现);
- 提供可选联系内容(下拉表单);
- 可插入到模板的任意位置,不局限于新建页面使用。
如果你对上面的内容有兴趣,就继续看吧。
首先是表单的构成,代码如下:
<ol class="forms">
<li><label for="contactName">your name</label>
<input type="text" name="contactName" id="contactName" value="<?php if(isset($_POST['contactName'])) echo $_POST['contactName'];?>" class="requiredField" />
<?php if($nameError != '') { ?>
<span class="error"><?=$nameError;?></span>
<?php } ?>
</li>
<li><label for="email">your E-mail</label>
<input type="text" name="email" id="email" value="<?php if(isset($_POST['email'])) echo $_POST['email'];?>" class="requiredField email" />
<?php if($emailError != '') { ?>
<span class="error"><?=$emailError;?></span>
<?php } ?>
</li>
<li class="textarea"><label for="commentsText">your words</label>
<textarea name="comments" id="commentsText" rows="20" cols="30" class="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 class="inline"><input type="checkbox" name="sendCopy" id="sendCopy" value="true"<?php if(isset($_POST['sendCopy']) && $_POST['sendCopy'] == true) echo ' checked="checked"'; ?> /><label for="sendCopy">Send a copy of this email to yourself</label></li>
<li class="screenReader"><label for="checking" class="screenReader">If you want to submit this form, do not enter anything in this field</label><input type="text" name="checking" id="checking" class="screenReader" value="<?php if(isset($_POST['checking'])) echo $_POST['checking'];?>" /></li>
<li class="buttons"><input type="hidden" name="submitted" id="submitted" value="true" /><button type="submit">Send to Jinwen »</button></li>
</ol>
基本上表单这样构成,能看到的是常见的name,mail,comment三个部分,这些都是通用的,大家无需更改。至于倒数第二个list中的screenReader是用来防止垃圾留言的,有兴趣的朋友可以看这篇介绍文章。还有就是上面代码中的一些变量部分(带$部分),看不看得懂也无所谓的,这些是用来检测填写内容的正确与否。
有了上面的代码部分,接着我们需要一个无错提交表单后的欢迎信息,代码如下:
<?php if(isset($emailSent) && $emailSent == true) { ?>
<div class="thanks">
<h1>Thanks, <?=$name;?></h1>
<p>你的邮件已成功发送!我会尽快与你联系。Have a nice day ^_^ </p>
</div>
<?php } else { ?>
<?php if(isset($hasError) || isset($captchaError)) { ?>
<p class="error">There was an error submitting the
<?php } ?>
<form action="http://www.saywp.com" id="contactForm" method="post">
*****在这里插入上面一段代码<ol>...</ol>*****
</form>
<?php } ?>
到这里要说明的是基本上上面的代码都可以全用,需要注意的是你必需修改如下一句中的网址为你表单所在页面的位置,否则提交不会成功的。
<form action="http://www.saywp.com" id="contactForm" method="post">
至此,我们完成了contact form中的基本部分,我先写到这里,在下一篇我继续写表单内容的判断部分代码,感兴趣的朋友下篇见。