Files
OTSSigns-Website/theme/inc/ajax.php
Matt Batchelder 19ee98c68d init
2026-02-20 21:28:00 -05:00

65 lines
2.0 KiB
PHP

<?php
/**
* AJAX Contact Form Handler
*
* Receives submissions from the oribi/contact-section block form,
* validates input, and sends an email via wp_mail().
*
* @package OTS_Theme
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
add_action( 'wp_ajax_oribi_contact', 'oribi_handle_contact' );
add_action( 'wp_ajax_nopriv_oribi_contact', 'oribi_handle_contact' );
/**
* Process the contact form AJAX request.
*/
function oribi_handle_contact() {
// Verify nonce
if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'oribi_contact_nonce' ) ) {
wp_send_json_error( 'Security check failed. Please refresh the page and try again.' );
}
$name = isset( $_POST['name'] ) ? sanitize_text_field( wp_unslash( $_POST['name'] ) ) : '';
$email = isset( $_POST['email'] ) ? sanitize_email( wp_unslash( $_POST['email'] ) ) : '';
$interest = isset( $_POST['interest'] ) ? sanitize_text_field( wp_unslash( $_POST['interest'] ) ) : '';
$message = isset( $_POST['message'] ) ? sanitize_textarea_field( wp_unslash( $_POST['message'] ) ) : '';
// Validate required fields
if ( empty( $name ) || empty( $email ) || empty( $message ) ) {
wp_send_json_error( 'Please fill in all required fields.' );
}
if ( ! is_email( $email ) ) {
wp_send_json_error( 'Please enter a valid email address.' );
}
// Build the email
$to = get_option( 'admin_email' );
$subject = sprintf( '[OTS Theme] New inquiry from %s', $name );
$body = sprintf(
"Name: %s\nEmail: %s\nInterested In: %s\n\nMessage:\n%s",
$name,
$email,
$interest ? $interest : 'Not specified',
$message
);
$headers = [
'Content-Type: text/plain; charset=UTF-8',
sprintf( 'Reply-To: %s <%s>', $name, $email ),
];
$sent = wp_mail( $to, $subject, $body, $headers );
if ( $sent ) {
wp_send_json_success( "Thanks! We'll get back to you shortly." );
} else {
wp_send_json_error( 'Something went wrong. Please try again or email us directly.' );
}
}