我目前正在努力构建我的第一个Wordpress联系我们插件,用于我目前正在处理的网站。
到目前为止,我取得了以下进展 -
我被困在流程的表单提交部分,我使用AJAX提交表单而不刷新页面。我不确定如何在不刷新页面的情况下提交表单,并且在此过程中,包含表单响应的电子邮件将发送到管理员电子邮件并发布到数据库和WP仪表板。
我已经在下方提供了所有代码 - 如果有人可以帮助我并使其正常运行,我将不胜感激。
contact_us_form.php
<?php
/*
Plugin Name: Contact Us Form Plugin
Plugin URI: iphonerepair.ie
Description: Contact us form with validaton - sends email and posts responses to database and WP dashboard.
Version: 1.0
Author URI: jms-design.co.uk
*/
if(!defined('WPINC'))
{
die;
}
// create table at plugin activition
register_activation_hook( __FILE__, 'jms_create_db' );
function jms_create_db()
{
global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
$table_name=$wpdb->prefix.'contactusform';
$sql="CREATE TABLE $table_name(
id mediumint(9) NOT NULL AUTO_INCREMENT,
time datetime DEFAULT NULL,
name varchar(50) DEFAULT NULL,
telno int(20) DEFAULT NULL,
email varchar(75) DEFAULT NULL,
town varchar(75) DEFAULT NULL,
device varchar(75) DEFAULT NULL,
message text,
UNIQUE KEY id (id)
) $charset_collate;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
}
//adding plugin to admin menu
add_action('admin_menu', 'jms_menu');
function jms_menu()
{
add_menu_page(__('Contact Form','jms'), __('Contact Form','jms'),
'administrator', 'jms-contact-form', 'jms_settings_page', 'dashicons-email');
function jms_settings_page()
{
global $wpdb;
$table_name=$wpdb->prefix.'contactusform';
$client_msg = $wpdb->get_results(
"
SELECT *
FROM $table_name
"
);
require_once(plugin_dir_path(__FILE__).'settings-page.php');
}
}
function cf_jms()
{
ob_start();
require_once(plugin_dir_path(__FILE__).'form.php');
return ob_get_clean();
}
add_shortcode( 'jms_contact_form', 'cf_jms' );
//if you want to have both logged in and not logged in users submitting, you have to add both actions!
add_action( 'admin_post_add_foobar', 'jms_admin_add_foobar' );
add_action( 'admin_post_nopriv_add_foobar', 'jms_admin_add_foobar' );
function jms_admin_add_foobar() {
global $wpdb;
$data = array(
'time' => current_time('mysql'),
'name' => sanitize_text_field( $_POST['name']),
'telno' => sanitize_text_field( $_POST['telno']),
'email' => isset( $_POST['email'] ) ? sanitize_email( $_POST['email']) : null,
'town' => sanitize_text_field( $_POST['town']),
'device' => sanitize_text_field( $_POST['device']),
'message' => sanitize_text_field( $_POST['message'])
);
$table_name = $wpdb->prefix.'starkod';
$headers = array( 'Content-Type: text/html; charset=UTF-8' );
// send Email for admin
wp_mail(
get_option( 'admin_email' ),
'Instant Qoute/Callback Form',
'Time : ' . $data['time'] .
'Name : ' . $data['name'] .
'Tel No : ' . $data['telno'] .
'Email : ' . $data['email'] .
'Town : ' . $data['town'] .
'Device : ' . $data['device'] .
' The message: ' . $data['message'],
$headers
);
if ( $wpdb->insert( $table_name, $data ) ) {
$_SESSION['message'] = "Your Message received , thanks ";
} else {
$_SESSION['message'] = "there's problem try again please";
}
//redirect back to where user was comming
wp_redirect( $_SERVER['HTTP_REFERER'] );
//request handlers should die() when they complete their task
}
?>
&#13;
form.php的
<form class="contactusform" method="post" novalidate="novalidate">
<?php
if(isset($_SESSION['message']))
{
echo $_SESSION['message'];
unset($_SESSION['message']);
}
?>
<input type="hidden" name="action" value="add_foobar">
<input type="hidden" name="data" value="foobarid">
<label>Full Name:</label><input type="text" name="name" value="" required="">
<label>Phone Number:</label><input type"=text" name="telno" value="" required="">
<label>Email Address:</label><input type="email" name="email" value="" required="">
<label>Town:</label><input type"=text" name="town" value="" required="">
<label>Device:</label><select name="device" value="" required="">
<option selected="selected" value=""></option><option value="Not Sure">Not Sure</option><option selected="selected" value=""></option><option value="iPhone 3G">iPhone 3G</option><option value="iPhone 3GS">iPhone 3GS</option><option value="iPhone 4G">iPhone 4G</option><option value="iPhone 4S">iPhone 4S</option><option value="iPhone 5">iPhone 5</option><option value="iPhone 5C">iPhone 5C</option><option value="iPhone 5S">iPhone 5S</option><option value="iPhone 6">iPhone 6</option><option value="iPhone 6 Plus">iPhone 6 Plus</option><option selected="selected" value=""></option><option value="MacBook">MacBook</option><option value="MacBook Pro">MacBook Pro</option><option value="MacBook Air">MacBook Air</option><option selected="selected" value=""></option><option value="iMac">iMac</option><option selected="selected" value=""></option><option value="iPad 1">iPad 1</option><option value="iPad 2">iPad 2</option><option value="iPad 3">iPad 3</option><option value="iPad 4">iPad 4</option><option value="iPad Air">iPad Air</option><option value="iPad Air 2">iPad Air 2</option><option value="iPad Mini 1">iPad Mini 1</option><option value="iPad Mini 2">iPad Mini 2</option><option value="iPad Mini 3">iPad Mini 3</option><option selected="selected" value=""></option><option value="iPod Classic">iPod Classic</option><option value="iPod Mini">iPod Mini</option><option value="iPod Nano">iPod Nano</option><option value="iPod Shuffle">iPod Shuffle</option><option value="iPod Touch">iPod Touch</option>
</select>
<label>Message:</label><textarea name="msg" cols="30" rows="4" value="" required=""></textarea>
<input class="submit2" type="submit">
</form>
<div id="success">
<p>Your message was sent successfully! I will be in touch as soon as I can.</p>
</div>
<div id="error">
<p>Something went wrong, try refreshing and submitting the form again.</p>
</div>
&#13;
settings-page.php
<div class="wrap">
<h3><?php esc_attr_e( 'Instant Quote/Callback Requests', 'jms' ); ?></h3>
<table class="widefat">
<thead>
<tr>
<th><?php esc_attr_e( 'Time', 'jms' ); ?></th>
<th><?php esc_attr_e( 'Name', 'jms' ); ?></th>
<th><?php esc_attr_e( 'Telephone Number', 'jms' ); ?></th>
<th><?php esc_attr_e( 'Email Address', 'jms' ); ?></th>
<th><?php esc_attr_e( 'Town', 'jms' ); ?></th>
<th><?php esc_attr_e( 'Device', 'jms' ); ?></th>
<th><?php esc_attr_e( 'Message', 'jms' ); ?></th>
</tr>
</thead>
<tbody>
<?php foreach($client_msg as $client): ?>
<tr>
<td><?php esc_attr_e($client->time,'jms');?></td>
<td><?php esc_attr_e($client->name,'jms');?></td>
<td><?php esc_attr_e($client->telno,'jms');?></td>
<td><?php esc_attr_e($client->email,'jms');?></td>
<td><?php esc_attr_e($client->town,'jms');?></td>
<td><?php esc_attr_e($client->device,'jms');?></td>
<td><?php esc_attr_e($client->msg,'jms');?></td>
</tr>
</tr>
<?php endforeach;?>
</tbody>
</table>
</div>
&#13;
验证码
<script src="//code.jquery.com/jquery-latest.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery.form/3.32/jquery.form.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.11.1/jquery.validate.min.js"></script>
<script type="text/javascript">
jQuery.validator.addMethod('answercheck', function (value, element) {
return this.optional(element) || /^\bcat\b$/.test(value);
}, "type the correct answer -_-");
// validate contact form
$(function() {
$('.contactusform').validate({
rules: {
name: {
required: true,
minlength: 2
},
telno: {
required: true,
minlength: 8,
number: true
},
email: {
required: true,
email: true
},
town: {
required: true,
minlength: 2
},
device: {
required: true
},
msg: {
required: true
},
},
messages: {
name: {
required: "Please enter your full name.",
minlength: "Your full name must consist of at least 2 characters."
},
telno: {
required: "Please enter your phone number.",
minlength: "Your phone number must consist of at least 8 characters."
},
email: {
required: "Please enter your email address."
},
town: {
required: "Please enter your town.",
minlength: "Your town must consist of at least 2 characters."
},
device: {
required: "Please select your device."
},
msg: {
required: "Please enter your message."
},
},
submitHandler: function(form) {
$(form).ajaxSubmit({
type:"POST",
data: $(form).serialize(),
url:"<?=admin_url()?>admin-post.php",
success: function() {
$('.contactusform :input').attr('disabled', 'disabled');
$('.contactusform').fadeTo( "slow", 0.15, function() {
$(this).find(':input').attr('disabled', 'disabled');
$(this).find('label').css('cursor','default');
$('#success').fadeIn();
});
},
error: function() {
$('#contactusform').fadeTo( "slow", 0.15, function() {
$('#error').fadeIn();
});
}
});
}
});
});
</script>
&#13;
process.php(不确定是否需要此代码......)
<?php
$to = "youremail@domain.com";
$from = $_REQUEST['email'];
$name = $_REQUEST['name'];
$headers = "From: $from";
$subject = "You have a message.";
$fields = array();
$fields{"name"} = "name";
$fields{"email"} = "email";
$fields{"phone"} = "phone";
$fields{"message"} = "message";
$body = "Here is what was sent:\n\n"; foreach($fields as $a => $b){ $body .= sprintf("%20s: %s\n",$b,$_REQUEST[$a]); }
$send = mail($to, $subject, $body, $headers);
?>
&#13;
如果有人能帮助我完成这项工作,我将非常感激。
非常感谢 约书亚
答案 0 :(得分:1)
这是我用于通常添加到wp_enqueue_script js文件夹的jquery
$(document).ready(function(){
// grab the submits button ID. do not use <input type="submit"> inside the form. Use a button instead outside the form.
$("#submit2").click(function()
{
// grab the forms ID
$("#message").submit(function(e)
{
// add a loading image in place of your returning outcome
$("#simple-msg").html("sending...");
// serialize/combine all submitted fields into an array
var postData = $(this).serializeArray();
// set url based of action
var formURL = $(this).attr("action");
// set ajax parameters
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
$("#simple-msg").html('<pre><code class="prettyprint">'+data+'</code></pre>');
},
error: function(jqXHR, textStatus, errorThrown)
{
$("#simple-msg").html('<pre><code class="prettyprint">AJAX Request Failed<br/> textStatus='+textStatus+', errorThrown='+errorThrown+'</code></pre>');
}
});
e.preventDefault(); //STOP default action
e.unbind();
});
$("#message").submit(); //SUBMIT FORM
});
});
我还使用所需字段更新了您的表单,但请记住您的表单操作,因为您需要指向处理表单的页面
<form name='message' id='message' class="contactusform" method="post" novalidate="novalidate" enctype="multipart/form-data" action="<?php echo plugins_url(); ?>/your-plugins-name/process.php">
<?php
if(isset($_SESSION['message']))
{
echo $_SESSION['message'];
unset($_SESSION['message']);
}
?>
<input type="hidden" name="action" value="add_foobar">
<input type="hidden" name="data" value="foobarid">
<label>Full Name:</label><input type="text" name="name" value="" required="">
<label>Phone Number:</label><input type"=text" name="telno" value="" required="">
<label>Email Address:</label><input type="email" name="email" value="" required="">
<label>Town:</label><input type"=text" name="town" value="" required="">
<label>Device:</label><select name="device" value="" required="">
<option selected="selected" value=""></option><option value="Not Sure">Not Sure</option><option selected="selected" value=""></option><option value="iPhone 3G">iPhone 3G</option><option value="iPhone 3GS">iPhone 3GS</option><option value="iPhone 4G">iPhone 4G</option><option value="iPhone 4S">iPhone 4S</option><option value="iPhone 5">iPhone 5</option><option value="iPhone 5C">iPhone 5C</option><option value="iPhone 5S">iPhone 5S</option><option value="iPhone 6">iPhone 6</option><option value="iPhone 6 Plus">iPhone 6 Plus</option><option selected="selected" value=""></option><option value="MacBook">MacBook</option><option value="MacBook Pro">MacBook Pro</option><option value="MacBook Air">MacBook Air</option><option selected="selected" value=""></option><option value="iMac">iMac</option><option selected="selected" value=""></option><option value="iPad 1">iPad 1</option><option value="iPad 2">iPad 2</option><option value="iPad 3">iPad 3</option><option value="iPad 4">iPad 4</option><option value="iPad Air">iPad Air</option><option value="iPad Air 2">iPad Air 2</option><option value="iPad Mini 1">iPad Mini 1</option><option value="iPad Mini 2">iPad Mini 2</option><option value="iPad Mini 3">iPad Mini 3</option><option selected="selected" value=""></option><option value="iPod Classic">iPod Classic</option><option value="iPod Mini">iPod Mini</option><option value="iPod Nano">iPod Nano</option><option value="iPod Shuffle">iPod Shuffle</option><option value="iPod Touch">iPod Touch</option>
</select>
<label>Message:</label><textarea name="msg" cols="30" rows="4" value="" required=""></textarea>
</form>
<input type='button' id='submit2' value='Send Message' />
<div id='simple-msg'></div>
希望这有帮助。