I usually try to avoid using preg_match()
, because I get the pattern right very rarely. Perhaps you could try using some other functions to do the validating. For example PHP’s ctype_alnum() for the name field and WP’s is_email() for the email field. Like so,
if ( $_POST['submission_name'] == '' ) {
$flag = 0;
echo "Please enter your name<br />";
} else if ( ! ctype_alnum( $_POST['submission_name'] ) ) { // ctype_alnum returns TRUE if every character in text is either a letter or a digit, FALSE otherwise.
$flag = 0;
echo "Please enter a valid name<br />";
}
if ( $_POST['submission_email'] == '' ) {
$flag = 0;
echo "Please enter your email address<br />";
} else if ( ! is_email( $_POST['submission_email'] ) ) {
$flag = 0;
echo "Please enter a valid email address<br />";
}
Also, if you want to make the wp_mail()
function a little bit more readable, you could do something like this,
$name = sanitize_text_field( $_POST['submission_name'] );
$email = sanitize_email( $_POST['submission_email'] );
$subject = sprintf(
'%s sent you a message from %s',
$name,
get_option("blogname")
);
$message = sanitize_textarea_field( $_POST['submission_message'] );
$from = sprintf(
"From: %s <%s>\r\n",
$name,
$email,
);
$reply_to .= sprintf(
"Reply-To: %s",
$email,
);
$headers = $from . $reply_to;
wp_mail(
get_option("admin_email"),
$subject,
$message,
$headers,
);