January 3, 2023 | Posted in WordPress
Are you looking for a way to allow visitors to your WordPress site to contact you? A contact form is an easy way to do this, and plenty of plugins are available to help you create one. This tutorial will show you how to create a simple contact form using a custom plugin.
<?php
/*
Plugin Name: My Contact Form Plugin
Description: A simple contact form plugin for WordPress.
*/
This is the opening PHP tag and the plugin header, which is required for all WordPress plugins. The plugin header specifies the plugin name and description, which are displayed in the WordPress plugin directory and the WordPress dashboard.
function my_contact_form_shortcode() {
ob_start();
?>
<form action="<?php echo esc_url( admin_url('admin-post.php') ); ?>" method="post">
<p>
<label for="name">Name:</label><br>
<input type="text" name="name" id="name" required>
</p>
<p>
<label for="email">Email:</label><br>
<input type="email" name="email" id="email" required>
</p>
<p>
<label for="message">Message:</label><br>
<textarea name="message" id="message" required></textarea>
</p>
<input type="hidden" name="action" value="my_contact_form_submit">
<p>
<input type="submit" value="Send Message">
</p>
</form>
<?php
return ob_get_clean();
}
The my_contact_form_shortcode
function generates the HTML code for the contact form and returns it. The function uses the ob_start
and ob_get_clean
functions to capture the output of the HTML code and return it as a string. This allows us to return the HTML code as the value of the function, which is necessary for using it as a shortcode.
The form includes fields for the visitor’s name, email, and message, as well as a submit button. The form action is set to admin-post.php
, which is a special WordPress script that allows plugin developers to handle form submissions. The action
hidden field specifies which function should be called when the form is submitted.
add_shortcode( 'my_contact_form', 'my_contact_form_shortcode' );
This line registers the my_contact_form_shortcode
function as a shortcode, which allows us to use the [my_contact_form]
shortcode to display the contact form on our WordPress site.
function my_contact_form_submit() {
// Validate form data
if ( ! isset( $_POST['name'], $_POST['email'], $_POST['message'] ) ) {
wp_die( 'Error: Invalid form data.' );
}
$name = sanitize_text_field( $_POST['name'] );
$email = sanitize_email( $_POST['email'] );
$message = sanitize_textarea_field( $_POST['message'] );
The my_contact_form_submit
function is called when the form is submitted. It begins by validating the form data to ensure that all required fields are present. If any of the required fields are missing, the function displays an error message and terminates.