Skip to content

Instantly share code, notes, and snippets.

@laxmariappan
Created October 16, 2024 11:29
Show Gist options
  • Select an option

  • Save laxmariappan/a63acb267459e2ce64386a14fc532d68 to your computer and use it in GitHub Desktop.

Select an option

Save laxmariappan/a63acb267459e2ce64386a14fc532d68 to your computer and use it in GitHub Desktop.
Learn WP - Contact Form Workshop Code
<?php
/**
* Plugin Name: WP Contact Form
* Description: WordPress Contact Form
* Version: 1.0.0
* Author: Lax, Jon
* Plugin URI: https://github.com/lax-mariappan/wp-contact-form
* Requires at least: 5.8
* Requires PHP: 8.0
* License: MIT
* Text Domain: wp-contact-form
*
* @package wp-contact-form
*/
// Exit if accessed directly.
if (! defined('ABSPATH')) {
exit;
}
// Adds shortcode for the form.
// [wp_contact_form] add this to editor to render the form wherever you like.
add_shortcode('wp_contact_form', 'wp_learn_contact_form');
/**
* Shortcode for the form.
*
* @return void
* @since 1.0.0
*/
function wp_learn_contact_form()
{
ob_start();
?>
<div class="wp-contact-form">
<form method="post" action="">
<label for="first_name">First Name</label>
<input type="text" id="first_name" name="first_name" required>
<label for="last_name">Last Name</label>
<input type="text" id="last_name" name="last_name" required>
<label for="subject">Subject</label>
<input type="text" id="subject" name="subject" required>
<label for="email">Email</label>
<input type="email" id="email" name="email" required>
<label for="message">Message</label>
<textarea id="message" name="message" required></textarea>
<input type="submit" name="submit" value="Submit">
</form>
</div>
<?php
return ob_get_clean();
}
// Enqueue scripts and styles.
add_action('wp_enqueue_scripts', 'wp_learn_enqueue_form_styles');
function wp_learn_enqueue_form_styles(){
wp_enqueue_style('wp-contact-form', plugin_dir_url(__FILE__) . '/css/style.css', array(), '1.0.0', 'all');
}
add_action('wp', 'wp_learn_handle_submission');
function wp_learn_handle_submission(){
if( isset( $_POST['submit'] ) ) {
// Sanitize the data.
$first_name = isset( $_POST['first_name'] ) ? sanitize_text_field( $_POST['first_name'] ) : '';
$email = isset( $_POST['email'] ) ? sanitize_email( $_POST['email'] ) : '';
$message = isset( $_POST['message'] ) ? sanitize_textarea_field( $_POST['message'] ) : '';
add_action('the_content', 'wp_learn_render_data');
}
}
function wp_learn_render_data( $content ){
$message = '<p>Thank you for contacting us. We will get back to you shortly.</p>';
return $content . $message;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment