PHP Developer

Monday, 20 October 2014

Create & Delete table in database at the time of Plugin Activation and Deactivation in WordPress

Create & Delete table in database at the time of Plugin Activation and Deactivation in WordPress

Create a plugin using this code & upload in WordPress and activate it, then check database, new table with name "wp_video_image" is add in database.

<?php
/*
Plugin Name: Create Table in Database
Plugin URI:
Description: This plugin helps you to to Create & Delete table in database at the time of plugin Activation and Deactivation. And also insert the values in plugin activation time.
Version: 0.1
Author: Sunil Sharma
Author URI: https://plus.google.com/u/0/115833273431242118637
*/

$paths = ABSPATH;  //absolute path
if(!defined('DS')){
    define('DS',DIRECTORY_SEPARATOR);
}
include_once $paths.'wp-load.php';
register_activation_hook(__FILE__,'vid_install');  //Function call at plugin activation
register_deactivation_hook(__FILE__ , 'vid_uninstall' );  // Function call at plugin Deactivation


function vid_install()
{
    global $wpdb;
    $table = wp_."video_image";
    $vidtab_query = "CREATE TABLE $table (
        id INT(11) NOT NULL AUTO_INCREMENT,
        video_name VARCHAR(100) NOT NULL,
        video_link VARCHAR(2000) NOT NULL,
        image_link VARCHAR(2000) NOT NULL,       
    UNIQUE KEY id (id)
    );";
    $wpdb->query($vidtab_query);
    $wpdb->insert(
    'wp_video_image',
    array( 
        'video_name' => 'Sunil Sharma',
        'video_link' => 'sunilsharma.mp4',
        'image_link' => 'sunil_sharma.png'
        )
    );
}
function vid_uninstall()
{
    global $wpdb;
    $table = wp_."video_image";
    $viddrop_query = "drop table if exists $table";
    $wpdb->query($viddrop_query); 
}
?>

No comments:

Post a Comment