至此,整个联系表单添加完成,contact.php文件的完整代码如下:
<?php
/*
Template Name:联系表单
*/
?>
<?php
if(isset($_POST['submit']) || isset($_POST['submit']) ) {
$body ='';
if(trim($_POST['owner'])) {
$body .= '<p>联系姓名:'.trim($_POST['owner']).'</p>';
}
if(trim($_POST['phone'])) {
$body .= '<p>联系电话:'.trim($_POST['phone']).'</p>';
}
if(trim($_POST['email'])) {
$body .= '<p>联系邮箱:'.trim($_POST['email']).'</p>';
}
if(trim($_POST['content'])) {
$body .= '<p>咨询内容:'.trim($_POST['content']).'</p>';
}
if(isset($body)) {
$emailTo = get_option('admin_email');
$sendmail = $_POST['email'];
$mailsubject = get_bloginfo('name').':'.$name;
$subject = '=?UTF-8?B?'.base64_encode($mailsubject).'?=';
$mailbody = $body;
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html; charset=utf-8"."\r\n";
$headers .="Content-Transfer-Encoding: 8bit"."\r\n";
$headers .= 'From: '.$name.' <'.$sendmail.'>' . "\r\n" . 'Reply-To: ' . $sendmail;
$state = wp_mail($emailTo, $subject, $mailbody, $headers);
if($state == true) {
wp_die('提交成功,点击<a href="'.get_bloginfo('url').'">返回首页</a>','需求提交成功');
}else{
wp_die('提交失败,点击<a href="'.get_bloginfo('url').'">返回首页</a>','需求提交失败');
}
}
}
?>
<?php get_header();?>
<div class="container">
<div class="main">
<?php while (have_posts()) : the_post(); ?>
<div class="post" id="post-<?php the_ID();?>">
<h1><?php the_content();?></h1>
<div class="entery">
<form id="contact-form" action="" method="post">
<p>
<label>姓名:<i>*</i></label>
<input type="text" name="owner" id="owner" class="text" value="<?php if(isset($_POST['owner'])) echo $_POST['owner'];?>" />
<span class="error"></span>
</p>
<p>
<label>联系电话:<i>*</i></label>
<input type="text" name="phone" id="phone" class="text" value="<?php if(isset($_POST['phone'])) echo $_POST['phone'];?>"/>
<span class="error"></span>
</p>
<p>
<label>联系邮箱:</label>
<input type="text" name="email" id="email" class="text" value="<?php if(isset($_POST['email'])) echo $_POST['email'];?>"/>
</p>
<p>
<label>咨询内容:<i>*</i></label>
<textarea name="content" id="content"><?php if(isset($_POST['content'])) echo $_POST['content'];?></textarea>
<span class="error"></span>
</p>
<p><input type="submit" name="submit" class="submit" value="提交需求"/></p>
</form>
</div>
</div>
<?php endwhile; ?>
</div>
</div>
<script type="text/javascript" src="<?php bloginfo('template_url');?>/js/contact.form.js"></script>
<?php get_footer();?>
然后在“后台——页面——新建页面”,在页面属性的模板中选择“联系表单”,然后发布该页面即可。
温馨提示:
1、该邮件联系表单使用wordpress内置函数wp_mail()发送,需要服务器开启mail()函数,否则无法发送邮件。
2、以上代码没有包含表单css样式,请自行编写美化!
1 2

