Friday, December 18, 2015

Wordpress : Creating Tables and additional data with Plugins

Hello to everyone. Today i will show you that how to create table and additional data with plugin in wordpress. So, please follow the steps below to have your plugin automatically create its database tables:
  1. Write a PHP function that creates the table.
  2. Ensure that WordPress calls the function when the plugin is activated.
  3. Create an upgrade function, if a new version of your plugin needs to have a different table structure.
Creating Database Table:
The first step in making your plugin create database tables automatically is to create a PHP function within your plugin that adds a table or tables to the WordPress MySQL database. Lets suppose that we want to create table_for_plugin function.

Database Table Prefix:
In the wp-config.php file, a WordPress site owner can define a database table prefix. By default, the prefix is "wp_", but we'll need to check on the actual value and use it to define your database table name. This value is found in the $wpdb->prefix variable. 

So, if we want to create a table called mypluginconfig, the first few lines of your table-creation function will be:
function  () {
   global $wpdb;

   $table_name = $wpdb->prefix . "mypluginconfig"; 
}
The whole function for creating a table and adding initial data will be :

<?php

function table_for_plugin() {
 global $wpdb;
 global $jal_db_version;

 $table_name = $wpdb->prefix . 'mypluginconfig';
 
 $charset_collate = $wpdb->get_charset_collate();

 $sql = "CREATE TABLE $table_name (
  id mediumint(9) NOT NULL AUTO_INCREMENT,
  time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
  name tinytext NOT NULL,
  text text NOT NULL,
  url varchar(55) DEFAULT '' NOT NULL,
  UNIQUE KEY id (id)
 ) $charset_collate;";

 require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
 dbDelta( $sql );

 
}

function plugin_install_data() {
 global $wpdb;
 
 $welcome_name = 'Mr. WordPress';
 $welcome_text = 'Congratulations, you just completed the installation!';
 
 $table_name = $wpdb->prefix . 'mypluginconfig';
 
 $wpdb->insert( 
  $table_name, 
  array( 
   'time' => current_time( 'mysql' ), 
   'name' => $welcome_name, 
   'text' => $welcome_text, 
  ) 
 );
}
Calling the function:

Now that we have the initialization function defined, we want to make sure that WordPress calls this function when the plugin is activated by a WordPress administrator. To do that, we will use the activate_ action hook. If our plugin file is wp-content/plugins/plugindir/pluginfile.php, we'll add the following line to the main body of our plugin:
register_activation_hook( __FILE__, 'table_for_plugin' );
register_activation_hook( __FILE__, 'plugin_install_data' );

This is how we add new table and initial data with plugin installation.

No comments:

Post a Comment