Skip to content

Instantly share code, notes, and snippets.

@fahidjavid
Last active January 21, 2020 08:43
Show Gist options
  • Save fahidjavid/2413dd5e270e0a2e187792c19aefe05d to your computer and use it in GitHub Desktop.
Save fahidjavid/2413dd5e270e0a2e187792c19aefe05d to your computer and use it in GitHub Desktop.
A WordPress standard contact form and its request mail handler.
/*----------------------------------------------------------------------------------*/
/* Contact Form AJAX validation and submission
/* Validation Plugin : http://bassistance.de/jquery-plugins/jquery-plugin-validation/
/* Form Ajax Plugin : http://www.malsup.com/jquery/form/
/*---------------------------------------------------------------------------------- */
if (jQuery().validate && jQuery().ajaxSubmit) {
var submitButton = $('#submit-button'),
ajaxLoader = $('#ajax-loader'),
messageContainer = $('#message-container'),
errorContainer = $("#error-container");
var formOptions = {
beforeSubmit: function () {
submitButton.attr('disabled', 'disabled');
ajaxLoader.fadeIn('fast');
messageContainer.fadeOut('fast');
errorContainer.fadeOut('fast');
},
success: function (ajax_response, statusText, xhr, $form) {
var response = $.parseJSON(ajax_response);
ajaxLoader.fadeOut('fast');
submitButton.removeAttr('disabled');
if (response.success) {
$form.resetForm();
messageContainer.html(response.message).fadeIn('fast');
} else {
errorContainer.html(response.message).fadeIn('fast');
}
}
};
$('#contact-form').each(function () {
$(this).validate({
errorLabelContainer: errorContainer,
submitHandler: function (form) {
$(form).ajaxSubmit(formOptions);
}
});
});
}
<?php
if ( ! function_exists( 'PREFIX_contact_form_shortcode' ) ) {
/**
* Contact form shortcode
*/
function PREFIX_contact_form_shortcode() {
$target_email = get_post_meta( get_the_ID(), 'PREFIX_contact_form_email', true );
?>
<form action="<?php echo esc_url( admin_url( 'admin-ajax.php' ) ); ?>" id="contact-form" method="post">
<input type="text" name="fname" placeholder="<?php esc_html_e( 'First Name', 'text-domain' ); ?>" title="<?php esc_html_e( '* Please enter your first name.', 'text-domain' ); ?>" class="required">
<input type="text" name="lname" placeholder="<?php esc_html_e( 'Last Name', 'text-domain' ); ?>">
<input type="text" name="phone" placeholder="<?php esc_html_e( 'Mobile', 'text-domain' ); ?>">
<input type="text" name="email" placeholder="<?php esc_html_e( 'Email', 'text-domain' ); ?>" title="<?php esc_html_e( '* Please enter your correct email.', 'text-domain' ); ?>" class="required email">
<textarea name="message" cols="30" rows="10" placeholder="<?php esc_html_e( 'Message', 'text-domain' ); ?>" title="<?php esc_html_e( '* Please enter your message.', 'text-domain' ); ?>" class="required"></textarea>
<div class="submission-area">
<input type="hidden" name="action" value="PREFIX_contact_request"/>
<input type="hidden" name="nonce" value="<?php echo wp_create_nonce( 'PREFIX_contact_request' ); ?>"/>
<input type="hidden" name="target" value="<?php echo antispambot( sanitize_email( $target_email ) ); ?>">
<input type="submit" id="submit-button" value="<?php esc_html_e( 'Submit', 'text-domain' ); ?>">
<img id="ajax-loader" src="<?php echo get_template_directory_uri() . 'img/ajax-loader.svg'; ?>" alt="<?php esc_html_e( 'Ajax Loader', 'text-domain' ); ?>">
</div>
</form>
<div id="error-container"></div>
<div id="message-container"></div>
<?php
}
add_shortcode( 'PREFIX_contact_form', 'PREFIX_contact_form_shortcode' );
}
<?php
if ( ! function_exists( 'PREFIX_contact_request' ) ) {
/**
* contact form email handler for common contact forms in WordPress
* @since 1.0.0
* @return void
*/
function PREFIX_contact_request() {
if ( isset( $_POST['email'] ) ):
$nonce = $_POST['nonce'];
if ( ! wp_verify_nonce( $nonce, 'PREFIX_contact_request' ) ) {
echo json_encode( array(
'success' => false,
'message' => esc_html__( 'Unverified Nonce!', 'text-domain' )
) );
die;
}
// Sanitize and Validate Target email address that is coming from agent form
$to_email = sanitize_email( $_POST['target'] );
$to_email = is_email( $to_email );
if ( ! $to_email ) {
echo wp_json_encode( array(
'success' => false,
'message' => esc_html__( 'Target Email address is not properly configured!', 'text-domain' )
) );
die;
}
/*
* Sanitize and Validate contact form input data
*/
$from_name = sanitize_text_field( $_POST['fname'] );
$last_name = sanitize_text_field( $_POST['lname'] );
$phone = sanitize_text_field( $_POST['phone'] );
$message = wp_kses_data( $_POST['message'] );
$from_email = sanitize_email( $_POST['email'] );
$from_email = is_email( $from_email );
if ( ! $from_email ) {
echo json_encode( array(
'success' => false,
'message' => esc_html__( 'Provided Email address is invalid!', 'text-domain' )
) );
die;
}
$email_subject = esc_html__( 'New message sent by', 'text-domain' ) . ' ' . $from_name . ' ' . esc_html__( 'using contact form at', 'text-domain' ) . ' ' . esc_html( get_bloginfo( 'name' ) );
$email_body = esc_html__( "You have received a message from: ", 'text-domain' ) . $from_name . ' ' . $last_name . " <br/>";
if ( ! empty( $phone ) ) {
$email_body .= esc_html__( "Phone Number: ", 'text-domain' ) . $phone . " <br/>";
}
$email_body .= esc_html__( "Their additional message is as follows:", 'text-domain' ) . " <br/><br/>";
$email_body .= wpautop( $message );
$email_body .= wpautop( sprintf( esc_html__( 'You can contact %1$s via email: %2$s', 'text-domain' ), $from_name, $from_email ) );
/*
* Email Headers ( Reply To and Content Type )
*/
$headers = array();
$headers[] = "Reply-To: $from_name <$from_email>";
$headers[] = "Content-Type: text/html; charset=UTF-8";
$headers = apply_filters( "PREFIX_contact_mail_header", $headers ); // just in case if you want to modify the header in child theme
if ( wp_mail( $to_email, $email_subject, $email_body, $headers ) ) {
echo json_encode( array(
'success' => true,
'message' => esc_html__( "Message Sent Successfully!", 'text-domain' )
) );
} else {
echo json_encode( array(
'success' => false,
'message' => esc_html__( "Server Error: WordPress mail function failed!", 'text-domain' )
)
);
}
else:
echo json_encode( array(
'success' => false,
'message' => esc_html__( "Invalid Request !", 'text-domain' )
)
);
endif;
die;
}
add_action( 'wp_ajax_nopriv_PREFIX_contact_request', 'PREFIX_contact_request' );
add_action( 'wp_ajax_PREFIX_contact_request', 'PREFIX_contact_request' );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment