Home > Article > Backend Development > Simplify contact form creation with basic requirements
Whether you are starting a simple blog, creating a corporate website or building a creative portfolio with WordPress, a Contact Us page is (almost) always a necessity, and having a contact form is (almost) always Better than sharing your email address publicly (although spam bots love them). Sure, there are tons of great contact form plugins for WordPress, but why bloat the site with a heavy plugin with lots of database queries when we can use a lovely, simple custom shortcode plugin instead?
Plugins are great, but too many of them have features you don’t need and can bloat your site by using database connections, running extra PHP code, adding CSS stylesheets and JS files to the header …So, at some point, you just want to move away from existing plugins, no matter how great the plugins you want to use are.
If you don't know how to code, I must admit that your hands are (somewhat) tied and you have to use a plugin. However, if you're familiar with WordPress development at any level (and I'm assuming you are, since you're still with me), then you should consider the benefits of hacking your own theme or writing your own plugin. The following are the advantages in my opinion:
Okay, enough chit-chat – let’s start coding! We're not going to be dealing with a ton of code or any kind of hard work here, so even if you're a beginner at PHP and/or WordPress, you can understand the code by following my guide and studying any part of it. Code you don't recognize.
You can put this code directly into your theme's functions.php file, but a better way is to use it as a plugin. This way when you switch themes you don't lose functionality and end up printing shortcodes in your content. Let's start with the standard plugin information:
<?php /* Plugin Name: Simple Contact Form Shortcode Plugin URI: https://tutsplus.com/authors/Bar%C4%B1%C5%9F%20%C3%9Cnver Description: A simple contact form for simple needs. Usage: <code>[contact email="your@email.address"]</code> Version: 1.0 Author: Barış Ünver Author URI: http://beyn.org/ */ // This line of comment holds the place of the amazingly simple code we're going to write. So you don't really need to read this. ?>
get_the_ip()
As you can guess from the function name, we get the user's real IP address even if the user is connecting through a proxy server. Of course, it's not foolproof, but we use it anyway as additional information for users.
Basically, we'll try to get the different $_SERVER
variables: HTTP_X_FORWARDED_FOR
, HTTP_CLIENT_IP
, and REMOTE_ADDR
respectively. code show as below:
function wptuts_get_the_ip() { if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) { return $_SERVER["HTTP_X_FORWARDED_FOR"]; } elseif (isset($_SERVER["HTTP_CLIENT_IP"])) { return $_SERVER["HTTP_CLIENT_IP"]; } else { return $_SERVER["REMOTE_ADDR"]; } }
If you follow my posts on Wptuts, you know that I absolutely love the Shortcode API for WordPress.
I will divide the shortcode into 3 parts to explain it better, but let's not forget to turn the shortcode feature on and off first:
function wptuts_contact_form_sc( $atts ) { // This line of comment, too, holds the place of the brilliant yet simple shortcode that creates our contact form. And yet you're still wasting your time to read this comment. Bravo. } add_shortcode( 'contact', 'wptuts_contact_form_sc' );
We need to set some properties in order to remain flexible while remaining lightweight. Here are ten:
extract( shortcode_atts( array( // if you don't provide an e-mail address, the shortcode will pick the e-mail address of the admin: "email" => get_bloginfo( 'admin_email' ), "subject" => "", "label_name" => "Your Name", "label_email" => "Your E-mail Address", "label_subject" => "Subject", "label_message" => "Your Message", "label_submit" => "Submit", // the error message when at least one of the required fields are empty: "error_empty" => "Please fill in all the required fields.", // the error message when the e-mail address is not valid: "error_noemail" => "Please enter a valid e-mail address.", // and the success message when the e-mail is sent: "success" => "Thanks for your e-mail! We'll get back to you as soon as we can." ), $atts ) );
Remember that we will reference them in the code as variables with attribute names (e.g. $label_submit
).
This is the most important part of the function, so I will continue to explain the code in the code , with the commented line:
// if the <form> element is POSTed, run the following code if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) { $error = false; // set the "required fields" to check $required_fields = array( "your_name", "email", "message", "subject" ); // this part fetches everything that has been POSTed, sanitizes them and lets us use them as $form_data['subject'] foreach ( $_POST as $field => $value ) { if ( get_magic_quotes_gpc() ) { $value = stripslashes( $value ); } $form_data[$field] = strip_tags( $value ); } // if the required fields are empty, switch $error to TRUE and set the result text to the shortcode attribute named 'error_empty' foreach ( $required_fields as $required_field ) { $value = trim( $form_data[$required_field] ); if ( empty( $value ) ) { $error = true; $result = $error_empty; } } // and if the e-mail is not valid, switch $error to TRUE and set the result text to the shortcode attribute named 'error_noemail' if ( ! is_email( $form_data['email'] ) ) { $error = true; $result = $error_noemail; } if ( $error == false ) { $email_subject = "[" . get_bloginfo( 'name' ) . "] " . $form_data['subject']; $email_message = $form_data['message'] . "\n\nIP: " . wptuts_get_the_ip(); $headers = "From: " . $form_data['name'] . " <" . $form_data['email'] . ">\n"; $headers .= "Content-Type: text/plain; charset=UTF-8\n"; $headers .= "Content-Transfer-Encoding: 8bit\n"; wp_mail( $email, $email_subject, $email_message, $headers ); $result = $success; $sent = true; } // but if $error is still FALSE, put together the POSTed variables and send the e-mail! if ( $error == false ) { // get the website's name and puts it in front of the subject $email_subject = "[" . get_bloginfo( 'name' ) . "] " . $form_data['subject']; // get the message from the form and add the IP address of the user below it $email_message = $form_data['message'] . "\n\nIP: " . wptuts_get_the_ip(); // set the e-mail headers with the user's name, e-mail address and character encoding $headers = "From: " . $form_data['your_name'] . " <" . $form_data['email'] . ">\n"; $headers .= "Content-Type: text/plain; charset=UTF-8\n"; $headers .= "Content-Transfer-Encoding: 8bit\n"; // send the e-mail with the shortcode attribute named 'email' and the POSTed data wp_mail( $email, $email_subject, $email_message, $headers ); // and set the result text to the shortcode attribute named 'success' $result = $success; // ...and switch the $sent variable to TRUE $sent = true; } }
This part is of course as important as the previous part. After all, how can the previous code send an email without a contact form? :)
// if there's no $result text (meaning there's no error or success, meaning the user just opened the page and did nothing) there's no need to show the $info variable if ( $result != "" ) { $info = '<div class="info">' . $result . '</div>'; } // anyways, let's build the form! (remember that we're using shortcode attributes as variables with their names) $email_form = '<form class="contact-form" method="post" action="' . get_permalink() . '"> <div> <label for="cf_name">' . $label_name . ':</label> <input type="text" name="your_name" id="cf_name" size="50" maxlength="50" value="' . $form_data['your_name'] . '" /> </div> <div> <label for="cf_email">' . $label_email . ':</label> <input type="text" name="email" id="cf_email" size="50" maxlength="50" value="' . $form_data['email'] . '" /> </div> <div> <label for="cf_subject">' . $label_subject . ':</label> <input type="text" name="subject" id="cf_subject" size="50" maxlength="50" value="' . $subject . $form_data['subject'] . '" /> </div> <div> <label for="cf_message">' . $label_message . ':</label> <textarea name="message" id="cf_message" cols="50" rows="15">' . $form_data['message'] . '</textarea> </div> <div> <input type="submit" value="' . $label_submit . '" name="send" id="cf_send" /> </div> </form>';
Tip: If you look closely at the HTML code of the contact form, you may see an additional $subject
variable. Remember the shortcode attribute "subject" that had no default value? This means that if you want to set a default theme, you can use a shortcode like this: [contact subject="Job application"]
返回简码的
最后一点非常简单:如果电子邮件已发送,则显示成功消息,或者显示电子邮件表单和错误消息(如果有)。代码如下:
if ( $sent == true ) { return $info; } else { return $info . $email_form; }
如果电子邮件已发送,我们不会再次显示该表单,但如果您仍想显示该表单,可以使用以下简单的行:
return $info . $email_form;
当然,代码本身看起来不太好。通过一些化妆、CSS,我们可以使我们的表单更漂亮。将这些 CSS 代码行添加到主题的 style.css 文件中:
.contact-form label, .contact-form input, .contact-form textarea { display: block; margin: 10px 0; } .contact-form label { font-size: larger; } .contact-form input { padding: 5px; } #cf_message { width: 90%; padding: 10px; } #cf_send { padding: 5px 10px; }
如果一切正确,您将看到类似于下图的内容:
恭喜,您刚刚构建了自己的联系表单短代码!
这个简单的联系表单对于大多数网站来说已经足够了,但是如果您想向其中添加更多字段,您只需编辑表单并将 $form_data['name_of_the_new_field']
变量添加到 $email_message
中变量(并且可能将字段名称添加到 $required_fields
数组中。
如果您对如何改进此代码或显示您使用该代码的网站页面有任何想法,请在下面与我们分享您的评论!
The above is the detailed content of Simplify contact form creation with basic requirements. For more information, please follow other related articles on the PHP Chinese website!