Custom Shortcode for a Contact Form

Create a shortcode that generates a contact form.

<?php
function custom_contact_form_shortcode() {
    ob_start(); ?>
    <form action="" method="post" id="contact-form">
        <label for="name">Name:</label>
        <input type="text" name="name" id="name" required />
        <label for="email">Email:</label>
        <input type="email" name="email" id="email" required />
        <label for="message">Message:</label>
        <textarea name="message" id="message" required></textarea>
        <input type="submit" value="Send" />
    </form>
    <?php
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        $name = sanitize_text_field($_POST['name']);
        $email = sanitize_email($_POST['email']);
        $message = sanitize_textarea_field($_POST['message']);
        
        $to = get_option('admin_email');
        $subject = 'Contact Form Submission';
        $headers = array('Content-Type: text/html; charset=UTF-8');
        $body = "Name: $name<br>Email: $email<br>Message: $message";
        
        wp_mail($to, $subject, $body, $headers);
        echo '<p>Thank you for your message!</p>';
    }
    return ob_get_clean();
}
add_shortcode('contact_form', 'custom_contact_form_shortcode');
?>

Post Comment