search
HomeBackend DevelopmentPHP TutorialSimplify 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?


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.

?>

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"];
	}
}

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' );

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 ) );

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;
	}
}

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>';

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,我们可以使我们的表单更漂亮。将这些 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; }

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

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
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
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

See all articles

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

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),