Build WordPress Plugin from Scratch with Custom Table

You can build a WordPress plugin by using WordPress existing tables. But situation may arise when you need to use custom table although its has some disadvantages. For a beginner to build a plugin with custom table for your blog or site might be seen tough. In this WordPress plugin development tutorial we will try our best to show the best possible easy way to build WordPress plugin from scratch with custom table. So we are going to build a plugin with two fields one is title and another one is date. Lets do it.

First make a php file name mtgpluginstest.php in your plugins folder and open the file. Most important part of a wordpress plugin is the header part. So lets make header. Place the following code in your mtgpluginstest.php file:

[html]<?php
/*
Plugin Name: How to Build A Plugin
Plugin URI: http://mytutorialguru.com
Description: How to build a wordpress plugin from Scratch with custom table.
Version: 1.1
Author: My Tutorial Guru
Author URI: http://mytutorialguru.com

Copyright 2014  My Tutorial Guru  (email : contact@mytutorialguru.com)

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/[/html]

At this stage you will see the first glimpse of your plugin in the plugins list:
Build WordPress Plugin from Scratch with Custom TableNext part is to register all necessary Scripts and CSS:

[php]function mtgpluginstest_enqeue_scripts(){
if (get_current_screen()->id == ‘menu-title_page_mtgpluginstest_the_form_page’)
{
wp_register_style(‘datepicker-style’, ‘/wp-content/plugins/’ . basename(dirname(__FILE__)) . ‘/css/jquery-ui-datepicker.css’);
wp_enqueue_style(‘datepicker-style’);
wp_register_script(‘mtgpluginstest-admin-functions’, get_bloginfo(‘url’) . ‘/wp-content/plugins/’ . basename(dirname(__FILE__)) . ‘/js/mtgpluginstest-admin-functions.js’);
wp_enqueue_script(‘mtgpluginstest-admin-functions’);
wp_enqueue_script(‘jquery’);
wp_enqueue_script(‘jquery-ui-datepicker’);

}
if (get_current_screen()->id == ‘toplevel_page_mtgpluginstest’)
{
wp_register_style(‘mtgpagination’, ‘/wp-content/plugins/’ . basename(dirname(__FILE__)) . ‘/css/mtgpagination.css’);
wp_enqueue_style(‘mtgpagination’);
}
}
add_action(‘admin_enqueue_scripts’, ‘mtgpluginstest_enqeue_scripts’);[/php]

Next step is to Create the Menu and Submenu:

[php]function mtgpluginstest_form_page(){
mtgpluginstest_get_list_form_page();
}
function mtgpluginstest_page_menu(){
add_menu_page( ‘Title’, ‘Menu Title’, ‘manage_options’, ‘mtgpluginstest’, ‘mtgpluginstest_form_page’, path_join(WP_PLUGIN_URL, basename(dirname(__FILE__)).’/images/mtg-plugintest-icon.png’), 768 );
}
add_action( ‘admin_menu’, ‘mtgpluginstest_page_menu’ );

////////////////////////START Creating Sub menu//////////////
function mtgpluginstest_add_submenu_form_page(){
mtgpluginstest_get_the_form_page();
}
function mtgpluginstest_add_submenu(){
add_submenu_page( ‘mtgpluginstest’, ‘Add New’, ‘Add New Data’, ‘manage_options’, ‘mtgpluginstest_the_form_page’, ‘mtgpluginstest_add_submenu_form_page’ );
}
add_action( ‘admin_menu’, ‘mtgpluginstest_add_submenu’ );
[/php]

Now we are going to create the table mtgpluginstest_table_name with three fields table_name_id,  table_name_title,  table_name_date  and fix activation and deactivation hook:

[php]////////////////////////////////START Plugin Activation/////////////////////////////
function mtgpluginstest_activation(){
global $wpdb;
$req = "CREATE TABLE IF NOT EXISTS " . $wpdb->prefix . "mtgpluginstest_table_name(
table_name_id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
table_name_title VARCHAR (200),
table_name_date DATE
); ";
$wpdb->query($req);
}
register_activation_hook(__FILE__, ‘mtgpluginstest_activation’);
////////////////////////////////END Plugin Activation/////////////////////////////

////////////////////////////////START Plugin Deactivation/////////////////////////////
function mtgpluginstest_deactivation(){
global $wpdb;
$req = "DROP TABLE IF EXISTS " . $wpdb->prefix . "mtgpluginstest_table_name;";
$wpdb->query($req);
}
register_deactivation_hook(__FILE__, ‘mtgpluginstest_deactivation’);
////////////////////////////////END Plugin Deactivation/////////////////////////////[/php]

Now activate your plugin and you will fine a new menu in your WordPress admin menu list:

build WordPress plugin from scratch with custom table

Check your database and you will see that a new table wp_mtgpluginstest_table_name has been added with three fields:

Build WordPress Plugin from Scratch with Custom Table

 

Now just after the Menu Part add following help functions:

[html]function mtgpluginstest_help_meta_box(){
?>
<div class="inner-sidebar">
<div class="postbox">
<h3><span>Need help?</span></h3>
<div class="inside">
<p>Learn plugin details here <a href="http://mytutorialguru.com/build-wordpress-plugin-scratch-custom-table/"> Documentation</a></p>
<hr />
<p>You can <a href="http://mytutorialguru.com/contact-us/"> Send us email</a></p>
<hr />
<p>Looking for more free resource<a href="http://mytutorialguru.com/category/wordpress/wordpress-plugin/"> Check Other Plugins</a></p>
</div>
</div>
</div>
<?php
}[/html]

Now we are going to build the form to save and edit data:

[php]function mtgpluginstest_get_the_form_page(){
$msg = $_GET[‘msg’];
global $wpdb;
include("the_form_to_save_data.php");
}[/php]

Now build a page the_form_to_save_data.php and paste the following code:

[html]

<div class="wrap">
<?php if(!isset($_GET[‘table_name_id’])) { ?>
<h2><?php _e(‘Add New Data’); ?></h2>
<div class="metabox-holder has-right-sidebar">
<?php mtgpluginstest_help_meta_box(); ?>
<div id="post-body">
<div id="post-body-content">

<div class="postbox">
<h3><span style="color:#FF0000"><?php _e(‘Fields with * marked have to filled’); ?></span></h3>
<?php if(isset($msg)){ ?><div style="padding: 5px" class="updated"><b><?php if ($msg==’error’) { _e(‘Sorry…Failed to save. Necessary (*) Field cannot be empty’); } ?></b></div><?php } ?>
<div class="inside">
<form action="#" method="post" enctype="multipart/form-data">

<p>
<label for="table_name_title"><b><?php _e(‘*Title :’); ?></b></label><br>
<input type="text" name="table_name_title" id="table_name_title" class="regular-text">
<span class="description"><?php _e(‘You cannot left title empty .’); ?></span>
<span style="color:#FF0000"><?php if(isset($error_msg)) echo $error_msg;?></span>
</p>

<p>
<label for="table_name_date"><b><?php _e(‘Date :’); ?></b></label><br>
<input type="text" name="table_name_date" id="table_name_date"><br />
<span class="description"><?php _e(‘If left empty the date will be current date’); ?></span>
</p>

<input type="hidden" name="which" id="which" value="insert_new_data"/>
<input type="submit" value="<?php _e(‘Save Data’); ?>" class="button-primary">
</form>
</div>
</div>
</div>
</div>

</div>
<?php } else {
$table_name_id = $_GET[‘table_name_id’];
$msg = $_GET[‘msg’];
global $wpdb;
$item = $wpdb->get_row(‘SELECT * FROM ‘ . $wpdb->prefix . ‘mtgpluginstestt_table_name WHERE table_name_id=’ . $table_name_id);
?>
<h2><?php _e(‘Edit Data Details’); ?><a href="<?php bloginfo(‘url’); ?>/wp-admin/admin.php?page=mtgpluginstest_the_form_page" title="" class="add-new-h2">Add New Data</a></h2>
<?php if(isset($msg)){ ?><div style="padding: 5px" class="updated"><b><?php if ($msg==’added’) { _e(‘New Data added successfully’); } else if ($msg==’error’) { _e(‘Sorry…Failed to save. Necessary (*) Field cannot be empty’); } else { _e(‘Data edited successfully’); } ?></b></div><?php } ?>
<div class="metabox-holder has-right-sidebar">
<?php mtgpluginstest_help_meta_box(); ?>

<div id="post-body">
<div id="post-body-content">

<div class="postbox">
<h3><span style="color:#FF0000"><?php _e(‘Fields with * marked have to be filled’); ?></span></h3>
<div class="inside">
<form action="#" method="post" enctype="multipart/form-data">
<p>
<label for="table_name_title"><b><?php _e(‘*Title :’); ?></b></label><br>
<input type="text" name="table_name_title" id="table_name_title" value="<?php echo($item->table_name_title); ?>" class="regular-text">
<span class="description"><?php _e(‘You cannot left title empty.’); ?></span>
<span style="color:#FF0000"><?php if(isset($error_msg)) echo $error_msg;?></span>
</p>

<p>
<label for="table_name_date"><b><?php _e(‘Date :’); ?></b></label><br>
<input type="text" name="table_name_date" id="table_name_date" value="<?php if($item->table_name_date ==’0000-00-00′) { echo(”); } else { echo(date("m/d/Y", strtotime($item->table_name_date))); } ?>"><br />
<span class="description"><?php _e(‘If left empty the date will be current date’); ?></span>
</p>
<input type="hidden" name="table_name_id" id="table_name_id" value="<?php echo($table_name_id); ?>"/>
<input type="hidden" name="which" id="which" value="update_the_data"/>
<input type="submit" value="<?php _e(‘Update Data’); ?>" class="button-primary">
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<?php
}

[/html]

If you done everything right so far then go to Menu Title-> Add New Data and you will see the page:

Build WordPress Plugin from Scratch with Custom Table

 

Next part is to fix the list page to show all Data:

[html]

function mtgpluginstest_get_list_form_page(){
global $wpdb;
?>
<div class="wrap">
<?php
$table_name_id = $_GET[‘table_name_id’];
$action=$_GET[‘action’];
if (isset($_GET[‘delete’])) {
if ($_REQUEST[‘table_name_id’] != ”)
{

$table_cl = $wpdb->prefix . "mtgpluginstest_table_name";
$delete = "DELETE FROM ".$table_cl." WHERE table_name_id = ".$_REQUEST[‘table_name_id’]." LIMIT 1";
$results = $wpdb->query( $delete );
$msg = "<br />"."Item Delete Successfully!";
}
}
if( $action==” || $action==’list’ ) {
?>
<h2><?php _e(‘Data List ‘); ?><a href="<?php bloginfo(‘url’); ?>/wp-admin/admin.php?page=mtgpluginstest_the_form_page" title="" class="add-new-h2">Add New</a></h2>

<?php
$table1 = $wpdb->prefix . "mtgpluginstest_table_name";
$sterm=$_REQUEST[‘sterm’];
if($sterm!="")
{
$wh1 = ‘WHERE (table_name_title like "%’.$sterm.’%") ‘;
}
include(‘generate_pagination.php’);
$items = $wpdb->get_results( "SELECT *FROM $table1 ".$wh1." ORDER BY table_name_id DESC LIMIT ".$limits.",".$max);

if ( $items == null ) {
if ( $sterm == null ) {
?>
Your list is empty. Please <a href="<?php bloginfo(‘url’); ?>/wp-admin/admin.php?page=mtgpluginstest_the_form_page" title="">Add a New Data</a>
<?php
}
else{
?>
No data found by your search keyword "<font color="red"><?php echo $sterm;?></font>". Please Go Back to <a href="<?php bloginfo(‘url’); ?>/wp-admin/admin.php?page=mtgpluginstest" title="">Data List</a>
<?php
}
}
else {
?>
<form action="" method="post">
<p align="right">
<label for="sterm"><b><?php _e(‘Search :’); ?></b></label>
<input type="text" name="sterm" id="sterm" title="Search By Keyword"/>
<br>
</p>
</form>
<table class="widefat">
<script type="text/javascript">
function show_confirm(table_name_title, table_name_id)
{
var rpath1 = "";
var rpath2 = "";
var r=confirm(‘Are you confirm to delete "’+table_name_title+’"’);
if (r==true)
{
rpath1 = ‘<?php echo $_SERVER[‘REQUEST_URI’]; ?>’;
rpath2 = ‘&delete=y&table_name_id=’+table_name_id;
window.location = rpath1+rpath2;
}
}
</script>
<thead>
<tr>
<th class="row-title">Title</th>
<th>Create Date</th>

</tr>
</thead>
<tbody>

<?php
foreach ( $items as $item ) {
?>
<tr>
<td class="title column-title">
<a href="<?php echo get_bloginfo(‘url’);?>/wp-admin/admin.php?page=mtgpluginstest_the_form_page&action=list&&table_name_id=<?php echo $item->table_name_id ?>"><b><?php echo $item->table_name_title ?></b></a>
<div class="row-actions">
<span class="edit"><a href="<?php echo get_bloginfo(‘url’);?>/wp-admin/admin.php?page=mtgpluginstest_the_form_page&table_name_id=<?php echo $item->table_name_id ?>">Edit</a></span> |
<span class="submitdelete"><a onclick="show_confirm(‘<?php echo $item->table_name_title; ?>’,'<?php echo $item->table_name_id; ?>’);" href="#delete">Delete</a></span>
</div>
</td>
<td><?php echo date("m/d/Y", strtotime($item->table_name_date)) ;?></td>
</tr>
<?php
}
?>
</tbody>
<tfoot>
<tr>
<th class="row-title">Title</th>
<th>Create Date</th>
</tr>
</tfoot>
</table>
<div align="center"><?php echo pagination($totalposts,$p,$lpm1,$prev,$next,$targetpage);?></div>
<?php
}
}
}

[/html]

In line 29 we have included query for generating pagination. If don’t understand this part please check our previous post Solution  for WordPress pagination

At this stage go to Menu Title and you can see the list is empty

Build WordPress Plugin from Scratch with Custom Table

Now add the query to insert and update the data:

[php]

global $wpdb;
if($_POST[‘which’]==’insert_new_data’){
$err = 0;
$table_name_title = $_POST[‘table_name_title’];
$table_name_date = $_POST[‘date’];
$today = date(‘y-m-d’);
if ($table_name_date != NULL) {
$table_name_date = date("Y-m-d", strtotime($table_name_date));
} else {
$table_name_date = $today;
}

if( $table_name_title ==” )
{
$error_msg= "error";
$err++;
}

if($err == 0)
{
$wpdb->query($wpdb->prepare(‘
INSERT INTO ‘ . $wpdb->prefix . ‘mtgpluginstest_table_name(table_name_title,table_name_date)
VALUES( %s, %s)’ , $table_name_title,$table_name_date));
header (‘Location: ‘ . get_bloginfo(‘url’) . ‘/wp-admin/admin.php?page=mtgpluginstest_the_form_page&msg=added&table_name_id=’ . $wpdb->insert_id);
}
else{
header (‘Location: ‘ . get_bloginfo(‘url’) . ‘/wp-admin/admin.php?page=mtgpluginstest_the_form_page&msg=error’);
}
}
////////////////////////////////END Inserting DATA/////////////////////////////

////////////////////////////////START Updating DATA/////////////////////////////
if($_POST[‘which’]==’update_the_data’){
$err = 0;
$table_name_id = $_POST[‘table_name_id’];
$table_name_title = $_POST[‘table_name_title’];
$table_name_date = $_POST[‘date’];
$today = date(‘y-m-d’);
if ($table_name_date != NULL) {
$table_name_date = date("Y-m-d", strtotime($table_name_date));
} else {
$table_name_date = $today;
}

if( $table_name_title ==” )
{
$error_msg= "error";
$err++;
}

if($err == 0)
{
$wpdb->query($wpdb->prepare(‘UPDATE ‘ . $wpdb->prefix . ‘mtgpluginstest_table_name SET table_name_title = \” . $table_name_title . ‘\’, table_name_date =\”. $table_name_date . ‘\’ WHERE table_name_id=%d’, $table_name_id));
header (‘Location: ‘ . get_bloginfo(‘url’) . ‘/wp-admin/admin.php?page=mtgpluginstest_the_form_page&msg=edited&table_name_id=’ . $table_name_id);
}
else{
header (‘Location: ‘ . get_bloginfo(‘url’) . ‘/wp-admin/admin.php?page=mtgpluginstest_the_form_page&msg=error&table_name_id=’ . $table_name_id);
}
}

[/php]

And you are done. We have added a single data :

wordpress plugin with custom table

You can get complete version of the plugin in here WordPress Plugin with Custom Tab. In next tutorial we will show you How to create Shortcode in WordPress Plugin

 

Author: mytutorialguru

Share This Post On

Submit a Comment

Your email address will not be published. Required fields are marked *