我制作了我的第一个WP插件,它是一个联系表单-下面是代码:
<?php
/*
Plugin Name: Example Contact Form Plugin
Plugin URI: http://example.com
Description: Simple non-bloated WordPress Contact Form
Version: 1.0
Author: Agbonghama Collins
Author URI: http://w3guy.com
*/
function html_form_code() {
echo \'<form action="\' . esc_url( $_SERVER[\'REQUEST_URI\'] ) . \'" method="post">\';
echo \'<p>\';
echo \'Your Name (required) <br />\';
echo \'<input type="text" name="cf-name" pattern="[a-zA-Z0-9 ]+" value="\' . ( isset( $_POST["cf-name"] ) ? esc_attr( $_POST["cf-name"] ) : \'\' ) . \'" size="40" />\';
echo \'</p>\';
echo \'<p>\';
echo \'Your Email (required) <br />\';
echo \'<input type="email" name="cf-email" value="\' . ( isset( $_POST["cf-email"] ) ? esc_attr( $_POST["cf-email"] ) : \'\' ) . \'" size="40" />\';
echo \'</p>\';
echo \'<p>\';
echo \'Subject (required) <br />\';
echo \'<input type="text" name="cf-subject" pattern="[a-zA-Z ]+" value="\' . ( isset( $_POST["cf-subject"] ) ? esc_attr( $_POST["cf-subject"] ) : \'\' ) . \'" size="40" />\';
echo \'</p>\';
echo \'<p>\';
echo \'Your Message (required) <br />\';
echo \'<textarea rows="10" cols="35" name="cf-message">\' . ( isset( $_POST["cf-message"] ) ? esc_attr( $_POST["cf-message"] ) : \'\' ) . \'</textarea>\';
echo \'</p>\';
echo \'<p><input type="submit" name="cf-submitted" value="Send"/></p>\';
echo \'</form>\';
}
function deliver_mail() {
// if the submit button is clicked, send the email
if ( isset( $_POST[\'cf-submitted\'] ) ) {
// sanitize form values
$name = sanitize_text_field( $_POST["cf-name"] );
$email = sanitize_email( $_POST["cf-email"] );
$subject = sanitize_text_field( $_POST["cf-subject"] );
$message = esc_textarea( $_POST["cf-message"] );
// get the blog administrator\'s email address
$to = get_option( \'admin_email\' );
$headers = "From: $name <$email>" . "\\r\\n";
// If email has been process for sending, display a success message
if ( wp_mail( $to, $subject, $message, $headers ) ) {
echo \'<div>\';
echo \'<p>Thanks for contacting me, expect a response soon.</p>\';
echo \'</div>\';
} else {
echo \'An unexpected error occurred\';
}
}
}
function cf_shortcode() {
ob_start();
deliver_mail();
html_form_code();
return ob_get_clean();
}
add_shortcode( \'contact_form\', \'cf_shortcode\' );
?>
This 是我用来制作的教程。
当我把[contact_form]
在帖子或页面上,没有显示任何内容。。。无联系方式。
为什么表单不会出现?
SO网友:majick
不使用输出缓冲,您可以只设置一个字符串并返回它,而不使用echo,例如。
$result = \'\';
if ( wp_mail( $to, $subject, $message, $headers ) ) {
$result .= \'<div>\';
$result .= \'<p>Thanks for contacting me, expect a response soon.</p>\';
$result .= \'</div>\';
} else {
$result .= \'An unexpected error occurred\';
}
return $result;
。。。并对html\\u form\\u代码函数执行相同的操作。。。那么就做:
function cf_shortcode() {
$deliver = deliver_mail();
$form = html_form_code();
return $deliver.$form;
}