无论您是要创建一个简单的博客、创建一个公司网站还是使用 WordPress 构建一个创意作品集,“联系(我们)”页面(几乎)总是必要的,而且拥有联系表单(几乎)总是更好而不是公开分享您的电子邮件地址(尽管垃圾邮件机器人喜欢它们)。当然,WordPress 有很多很棒的联系表单插件,但是当我们可以使用一个可爱、简单的自定义短代码插件来代替时,为什么要使用带有大量数据库查询的繁重插件来使网站膨胀呢?
插件很棒,但是太多的插件具有您不需要的功能,可能会通过使用数据库连接、运行额外的 PHP 代码、向标头添加 CSS 样式表和 JS 文件来使您的网站变得臃肿......所以,在某些时候,您只是想远离现有的插件,无论您想要使用的插件有多棒。
如果你不知道如何编码,我必须承认你的手(有点)被束缚,并且你必须使用插件。但是,如果您熟悉任何级别的 WordPress 开发(我假设您熟悉,因为您仍然和我在一起),那么您应该考虑破解自己的主题或编写自己的插件的好处。以下是我认为的优点:
好了,闲聊就够了——让我们开始编码吧!我们不会在这里处理大量的代码或任何类型的艰苦工作,因此即使您是 PHP 和/或 WordPress 的初学者,您也可以通过跟随我的指导并研究其中的任何部分来理解代码。您不认识的代码。
可以将此代码直接放入主题的 functions.php 文件中,但更好的方法是将其用作插件。这样,当您切换主题时,您不会失去功能并最终在内容中打印短代码。让我们从标准插件信息开始:
<?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()
正如您从函数名称中可以猜到的那样,即使用户通过代理服务器进行连接,我们也会获取用户的真实 IP 地址。当然,它并不是万无一失的,但我们无论如何都会将其用作用户的额外信息。
基本上,我们将尝试获取不同的 $_SERVER
变量:分别为 HTTP_X_FORWARDED_FOR
、HTTP_CLIENT_IP
和 REMOTE_ADDR
。代码如下:
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"]; } }
如果您在 Wptuts+ 上关注我的帖子,您就会知道我绝对喜欢 WordPress 的 Shortcode API。
我将把短代码分为 3 个部分,以便更好地解释它,但我们不要忘记首先打开和关闭短代码功能:
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' );
我们需要设置一些属性,以便在保持轻量级的同时保持灵活性。这是十个:
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 ) );
请记住,我们将在代码中将它们作为带有属性名称的变量进行引用(例如 $label_submit
)。
这是该函数中最重要的部分,因此我将继续解释代码中的代码,并带有注释行:
// 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; } }
这部分当然和前一部分一样重要。毕竟,如果没有联系表单,前面的代码如何发送电子邮件呢? :)
// 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>';
提示:如果您仔细查看联系表单的 HTML 代码,您可能会看到额外的 $subject
变量。还记得没有默认值的简码属性“subject”吗?这意味着如果您想设置默认主题,您可以使用这样的短代码: [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
数组中。
如果您对如何改进此代码或显示您使用该代码的网站页面有任何想法,请在下面与我们分享您的评论!
以上是简化基本要求的联系表单创建的详细内容。更多信息请关注PHP中文网其他相关文章!