/** * Handle the Contact page form submission and email it to the site admin. */ function hc_handle_contact_submit() { if ( ! isset( $_POST['hc_contact_nonce'] ) || ! wp_verify_nonce( $_POST['hc_contact_nonce'], 'hc_contact_submit' ) ) { wp_safe_redirect( add_query_arg( 'contact', 'error', home_url( '/contact/' ) ) ); exit; } // Honeypot field: real users never fill this in. if ( ! empty( $_POST['hc_website'] ) ) { wp_safe_redirect( add_query_arg( 'contact', 'success', home_url( '/contact/' ) ) ); exit; } $name = isset( $_POST['name'] ) ? sanitize_text_field( wp_unslash( $_POST['name'] ) ) : ''; $email = isset( $_POST['email'] ) ? sanitize_email( wp_unslash( $_POST['email'] ) ) : ''; $message = isset( $_POST['message'] ) ? sanitize_textarea_field( wp_unslash( $_POST['message'] ) ) : ''; if ( empty( $name ) || empty( $message ) || ! is_email( $email ) ) { wp_safe_redirect( add_query_arg( 'contact', 'error', home_url( '/contact/' ) ) ); exit; } $to = get_option( 'admin_email' ); $subject = sprintf( '[Health Calculators] New contact message from %s', $name ); $body = "You have a new message from the Health Calculators contact form.\n\n" . "Name: {$name}\n" . "Email: {$email}\n\n" . "Message:\n{$message}\n"; $headers = array( 'Content-Type: text/plain; charset=UTF-8', "Reply-To: {$name} <{$email}>" ); $sent = wp_mail( $to, $subject, $body, $headers ); wp_safe_redirect( add_query_arg( 'contact', $sent ? 'success' : 'error', home_url( '/contact/' ) ) ); exit; } add_action( 'admin_post_hc_contact_submit', 'hc_handle_contact_submit' ); add_action( 'admin_post_nopriv_hc_contact_submit', 'hc_handle_contact_submit' );