Month: May 2016

Create table while activating the custom wordpress plugin

If you want create a database table while a activating the plugin then you have to register_activation_hook() function. The following code can be placed in your main plugin file. The function will create tables in your Database.


function myplugin_install() {
    global $wpdb; 
    $table_name = $wpdb->prefix . "mytable";
    $db_version = '1.0';
    /**Execute the sql statement to create table**/
    $sql = "CREATE TABLE IF NOT EXISTS " . $table_name . " (
        `ID` int(11) NOT NULL AUTO_INCREMENT,
        `field1` varchar(300) DEFAULT NULL,
		`field2` varchar(300) DEFAULT NULL,
		`field3` varchar(300) DEFAULT NULL,
		`field4` varchar(300) DEFAULT NULL,
		`field5` varchar(300) DEFAULT NULL,
		 PRIMARY KEY (`ID`));"; 
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
    add_option( "db_version", '1.0' );  
}
// plugin activation hook
register_activation_hook(__FILE__,'myplugin_install');

Then activate your plugin.If already activated then reactivate the plugin. It automatically create table in your database. That’s it.

Have any doubt, then comment here!

Show welcome message only once per day

If you want to display a welcome message or alert box then you have to add the following JavaScript in your file.

function setCookie(key, value) {
            var expires = new Date();
            expires.setTime(expires.getTime() + (1 * 24 * 60 * 60 * 1000));
            document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
        }

function getCookie(key) {
           var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
           return keyValue ? keyValue[2] : null;
        }
if(getCookie('pop')==null)
{
	setCookie('pop',1);
	alert("WELCOME");
}

That’s it. In this code alert box shows only once per day.

Have any doubt, then comment here!