Blog

Build WordPress Contact forms Plugin save to DB and send Email

Build WordPress Contact forms Plugin save to DB and send Email

we will try to code wordpress plugin for contact form that save to DB and send Email when it is submitted .

Make a directory with a plugin unique name in ‘/wp-content/plugins’ I will named starkod-contact-form.

Make blank index.php and write in it just : <?php

to prevent direct access to plugin directory .

Make php file with same name as the directory I will name it starkod-contact-form.php and write meta description for our plugin :

<?php
/*
Plugin Name: Starkod Contact form
Plugin URI: starkod.net
Description: Contact form save to DB and send Email Tutorial
Author: Bahjat Al-Mostafa
Version: 0.1.0
Author URI: starkod.net
Text Domain: starkod
*/

now our plugin will appear in plugin area at wordpress admin like this : strakod wordpress plugin img 1

to be sure this file not called directly write in starkod-contact-form.php

if(!defined('WPINC'))
{
die;
}

create table at plugin activation this table will store form fields

// create table at plugin activition
register_activation_hook( __FILE__, 'starkod_create_db' );
function starkod_create_db() 
{
	global $wpdb;
	$charset_collate = $wpdb->get_charset_collate();
	$table_name=$wpdb->prefix.'starkod';
	$sql="CREATE TABLE $table_name(
		id mediumint(9) NOT NULL AUTO_INCREMENT,
		time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
		name varchar(50) DEFAULT NULL,
		email varchar(75) DEFAULT NULL,
		msg text,
		UNIQUE KEY id (id)
		) $charset_collate;";
	require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
	dbDelta( $sql );
}

now activate the plugin and you will find wp_starkod table in your wordpress db
2

adding plugin to admin menu

//adding plugin to admin menu
add_action('admin_menu', 'starkod_menu');
function starkod_menu() 
{
 add_menu_page(__('Contact Form','starkod'), __('Contact Form','starkod'),
 	 'administrator', 'starkod-contact-form', 'starkod_settings_page', 'dashicons-email');
	function starkod_settings_page() 
	 {
	 	global $wpdb;
	 	$table_name=$wpdb->prefix.'starkod';
	 	$client_msg = $wpdb->get_results( 
			"
			SELECT *
			FROM $table_name
			"
		);
	 	require_once(plugin_dir_path(__FILE__).'setting-page.php');
	 }
	 
}

let’s create setting-page.php for see all stored messages in db this a view for our plugin .

<div class="wrap">
<h3><?php esc_attr_e( 'Contact Form Messages', 'starkod' ); ?</h3>
<table class="widefat">
<thead>
<tr>
<th class="row-title"><?php esc_attr_e( 'Name', 'starkod' ); ?></th>
<th><?php esc_attr_e( 'Email', 'starkod' ); ?></th>
<th><?php esc_attr_e( 'Message', 'starkod' ); ?></th>
<th><?php esc_attr_e( 'Time', 'starkod' ); ?></th>
</tr>
</thead>
<tbody>

</tbody>

</table>
</div>

this page will give basic table view
3

now we will make simple contact form as short code , form.php is a view save it in root directory for our plugin

<form method="post" action="<?=admin_url()?>admin-post.php">
	<?php
	if(isset($_SESSION['message'])) 
	{
	    echo $_SESSION['message'];
	    unset($_SESSION['message']);
	} 
	?>
	 <input type="hidden" name="action" value="add_foobar">
	 <input type="hidden" name="data" value="foobarid">
	 <input type="text" name="name" placeholder="name">
	 <input type="email" name="email" placeholder="email">
	<textarea name="msg" placeholder="message"></textarea>
	<input type="submit" >
</form>

add to starkod-contact-form.php our contact form short code

function cf_starkod()
{
 ob_start();
 require_once(plugin_dir_path(__FILE__).'form.php');
 return ob_get_clean();
}
add_shortcode( 'starkod_contact_form', 'cf_starkod' );

add our new shortcode to any page or post
4

now open the page where you add our shortcode

5

now we will write code to receive form fields when it is submitted

//if you want to have both logged in and not logged in users submitting, you have to add both actions!
add_action( 'admin_post_add_foobar', 'starkod_admin_add_foobar' );
add_action( 'admin_post_nopriv_add_foobar', 'starkod_admin_add_foobar' );
function starkod_admin_add_foobar()
{

global $wpdb;
$data=array(
'name' =&amp;amp;gt; sanitize_text_field($_POST['name']),
'email' =&amp;amp;gt; isset($_POST['email'])?sanitize_email($_POST['email']):null,
'msg' =&amp;amp;gt; sanitize_text_field($_POST['msg']),
'time' =&amp;amp;gt; current_time( 'mysql' )
);
$table_name=$wpdb-&amp;amp;gt;prefix.'starkod';
$headers = array('Content-Type: text/html; charset=UTF-8');
// send Email for admin
wp_mail( get_option( 'admin_email'), 'starkod Contact Form',
'Name : '.$data['name']. ' phone : '.$data['phone'].' email : '.$data['email'].' The message: '.$data['msg'].' Time : '.$data['time'] ,$headers);
if($wpdb-&amp;amp;gt;insert( $table_name, $data ))
{
$_SESSION['message'] = "Your Message received , thanks ";
}
else
{
$_SESSION['message'] = "there's problem try again please";
}
//redirect back to where user was comming
wp_redirect($_SERVER['HTTP_REFERER']);
//request handlers should die() when they complete their task
}

lets add session messages to our form html to show message for our user

<form method="post" action="<?=admin_url()?>admin-post.php">
 <?php
 if(isset($_SESSION['message']))
 {
 echo $_SESSION['message'];
 unset($_SESSION['message']);
 }
 ?>
 <input type="hidden" name="action" value="add_foobar">
. . .

lets add foreach loop to our setting page ( setting-page.php )

<tbody>
 <?php foreach($client_msg as $client): ?>
 <tr>
 <td><?php esc_attr_e($client->name,'starkod');?></td>
 <td><?php esc_attr_e($client->email,'starkod');?></td>
 <td><?php esc_attr_e($client->msg,'starkod');?></td>
 <td><?php esc_attr_e($client->time,'starkod');?></td>
 </tr>
 </tr>
 <?php endforeach;?>
 </tbody>
...

we get our messages like this
6

from here you can try to improve this plugin to be more production-ready and secure .