Table of Contents
Benefits of Building Your Own Contact Form
Code
Short Code
Attributes of our shortcode
Send email via email
Contact list
返回简码的
CSS
结论
Home Backend Development PHP Tutorial Simplify contact form creation with basic requirements

Simplify contact form creation with basic requirements

Sep 02, 2023 pm 01:09 PM

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?


Benefits of Building Your Own Contact Form

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:

  • Optimization - Using too much code, especially extra code you don’t need, can even exceed the limits of your hosting plan in some cases. But even if you have ample resources on your server, optimization is always beneficial to the health of your site.
  • Cleanliness - In addition to the health of your server, clean code has huge benefits for your website loading and parsing speed. By coding/hacking it yourself, you only have what you need to take advantage of simple features on your site without having to load a ton of content. You know, it's even good for SEO.
  • The Joy of Control - You should never underestimate the power of giving orders. Taking control of your website will definitely make you a more passionate designer/developer than using a bunch of ready-made code. That's why, although we've provided the complete code for those who don't want to, I personally don't think you should copy/paste the code here but write it yourself. Even if you enter the exact same code, you can see how the plugin works and feel the joy of taking control. honestly.

Code

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.

?>
Copy after login

A small auxiliary function: 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"];
	}
}
Copy after login

Short Code

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' );
Copy after login

Attributes of our shortcode

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 ) );
Copy after login

Remember that we will reference them in the code as variables with attribute names (e.g. $label_submit).

Send email via email

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;
	}
}
Copy after login

Contact list

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>';
Copy after login

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;
}
Copy after login

如果电子邮件已发送,我们不会再次显示该表单,但如果您仍想显示该表单,可以使用以下简单的行:

return $info . $email_form;
Copy after login

CSS

当然,代码本身看起来不太好。通过一些化妆、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; }
Copy after login

如果一切正确,您将看到类似于下图的内容:

Simplify contact form creation with basic requirements

恭喜,您刚刚构建了自己的联系表单短代码!


结论

这个简单的联系表单对于大多数网站来说已经足够了,但是如果您想向其中添加更多字段,您只需编辑表单并将 $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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

How does PHP type hinting work, including scalar types, return types, union types, and nullable types? How does PHP type hinting work, including scalar types, return types, union types, and nullable types? Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

See all articles