how to make wordpress widget plugin

How to make a wordpress adserv plugin

Today we will make a widget that can do

1. Rotation display ad tags , track impression, compare impression at even

In order to do this, we need an internal table , and setup this table during plugin setup.

In the wp-config.php file, a WordPress site owner can define a database table prefix. By default, the prefix is “wp_”, but you’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. (If you’re developing for a version of WordPress older than 2.0, you’ll need to use the $table_prefix global variable, which is deprecated in version 2.1).

So, if you want to create a table called (prefix)liveshoutbox, the first few lines of your table-creation function will be:

global $wpdb;

$table_name = $wpdb->prefix . “ad_rotation”;

Since we going to use this table later during query, it make sense to create a function that return this table name for later reuse.

function get_tablename () {
global $wpdb;

$table_name = $wpdb->prefix . “ad_rotation”;
}

CREATE TABLE IF NOT EXISTS $table_name (
`id` int(11) NOT NULL AUTO_INCREMENT,
`type` int(11) NOT NULL COMMENT ‘ 300 900 -1’,
`banner` text NOT NULL,
`impression` int(11) NOT NULL,
`current_period_minute` int(11) NOT NULL,
`totalimpression` int(11) NOT NULL,
`enabled` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `id` (`id`),
KEY `type` (`type`),
KEY `id_2` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;

A Good document from WordPress main dev site is https://codex.wordpress.org/Creating_Tables_with_Plugins. now, we have got the table creation SQL, we need to find a way to exec this sql when plug-in been installed.

So we come to today’s first wordpress built in function,

Examples
If you have a function called myplugin_activate() in the main plugin file at either

wp-content/plugins/myplugin.php or
wp-content/plugins/myplugin/myplugin.php
use this code:

function myplugin_activate() {

// Activation code here…
}
register_activation_hook( __FILE__, ‘myplugin_activate’ );

This will call the myplugin_activate() function on activation of the plugin.

If your plugin uses the singleton class pattern, add the activation hook like so:

class MyPlugin {
static function install() {
// do not generate any output here
}
}

register_activation_hook( __FILE__, array( ‘ad_rotation’, ‘_install’ ) );

https://codex.wordpress.org/Function_Reference/register_activation_hook

register_deactivation_hook( __FILE__, array( ‘CMAdChanger’, ‘_uninstall’ ) );

So we have our first code ready to test out. and we got an error.

One thing worth to poitn out, testing wordpress plug-in has do be done at wordpress sites and watch error output at the web error log ,

eg /var/log/apache2/cceye.com_error.log

2016/10/12 14:40:21 [error] 3514#0: *42992556 FastCGI sent in stderr: “PHP Fatal error: Call to undefined function get_tablename() in adrotation.php on line 68” while reading response header from upstream, client: 108.161.162.92, server: cceye.com, request: “GET /wp-admin/plugins.php?action=deactivate&plugin=adrotation%2Fadrotation.php&plugin_status=all&paged=1&s&_wpnonce=21cdd674ab HTTP/1.1”, upstream: “fastcgi://127.0.0.1:9000”, host: “www.cceye.com”

Ok, after fixing the the typo caused error, we move on next task: Show the form in backend to

1, allow add banner tag code in manage page
2, allow to show banner statics

let’s take a look of this https://codex.wordpress.org/Administration_Menus, ok, done. pretty long document. but here is the quick summary.

/** Step 2 (from text above). */
add_action( ‘admin_menu’, ‘my_plugin_menu’ );

/** Step 1. */
function my_plugin_menu() {
add_options_page( ‘Ad rotation Options’, ‘Ad Rotation’, ‘manage_options’, ‘my-unique-identifier’, ‘adrotation_options’ );
}

/** Step 3. */
function adrotation_options() {
if ( !current_user_can( ‘manage_options’ ) ) {
wp_die( __( ‘You do not have sufficient permissions to access this page.’ ) );
}
echo ‘

‘;
echo ‘

Here is where the form would go if I actually had options.

‘;
echo ‘

‘;
}

3, allow to select which type of tag to show in widget area.

Notice has right manage_options here is the list of all role and capabilite
https://codex.wordpress.org/Roles_and_Capabilities#update_core

Now I need to hold all the ad unit in memory so setting page can show it’s

ID,name,size,slot, TAG,IMPRESSION, 24 hours impression, total impression, enabled or not //size, slot

Now I have added admin menu, it’s time to insert data into the table we just created.

https://codex.wordpress.org/Class_Reference/wpdb

public function myAdminPage() {
// Echo the html here…
$adminpage=plugin_dir_path( __FILE__ ). ‘admin_ad.php’;

echo ‘This is the page contents ‘.$adminpage;

ob_start();
require_once $adminpage;
$content = ob_get_contents();
ob_end_clean();

echo $content;

}

prepare(

INSERT INTO $wpdb->postmeta
( post_id, meta_key, meta_value )
VALUES ( %d, %s, %s )
“,
10,
$metakey,
$metavalue
);
*/

#$tagcode = str_replace(“‘”, “\\'”, $_POST[‘bannercode’]);
#$name= str_replace(“‘”, “\\'”, $_POST[‘bannername’]);
/* $sqlquery=”INSERT INTO $tablename
(`id`, `name`, `size`, `type`, `banner`, `impression`, `current_period_minute`, `last_24h_impression`, `totalimpression`, `enabled`, `enabled_time`)
VALUES (NULL, %s ,%d ,%d,%s, ‘0’, ‘0’, ‘0’, ‘0’, ‘1’, CURRENT_TIMESTAMP)”;
*/
$sqlquery=”INSERT INTO $tablename (`id`, `name`, `size`, `type`, `banner`, `impression`, `current_period_minute`, `last_24h_impression`, `totalimpression`, `enabled`, `enabled_time`) VALUES (NULL, ‘”.$name.”‘,”.$size.”, “.$_POST[‘bannertype’].”,'”.$tagcode.”‘, ‘0’, ‘0’, ‘0’, ‘0’, ‘1’, CURRENT_TIMESTAMP)”;

#$sqlquery=$wpdb->prepare($sqlquery,$name,$_POST[‘bannertype’], $_POST[‘bannersize’],$tagcode);

$success=$wpdb->query($sqlquery);

#$success=$wpdb->query(“$sqlquery”);

if($success===false){
echo ‘Error saving banner’ ;
}
}

if (array_key_exists ( ‘update’, $_POST )) {
global $wpdb;

#$tagcode = str_replace(“‘”, “\\'”, $_POST[‘bannercode’]);
$sqlquery=”UPDATE “.$tablename.” SET `banner` = ‘”.$tagcode.”‘ , `enabled_time` = CURRENT_TIMESTAMP WHERE `wp_ad_rotation`.`id` =”. $_POST[‘id’].”;”;
$success=$wpdb->query(“$sqlquery”);

if($success===false){
echo ‘Error saving banner’ ;
}
}

if (array_key_exists ( ‘disable’, $_POST )) {
global $wpdb;

#$tagcode = str_replace(“‘”, “\\'”, $_POST[‘bannercode’]);
$sqlquery=”UPDATE “.$tablename.” SET `enabled` = 0 , `enabled_time` = CURRENT_TIMESTAMP WHERE `wp_ad_rotation`.`id` =”. $_POST[‘id’].”;”;
$success=$wpdb->query(“$sqlquery”);

if($success===false){
echo ‘Error saving banner’ ;
}
}

if (array_key_exists ( ‘enable’, $_POST )) {
global $wpdb;

#$tagcode = str_replace(“‘”, “\\'”, $_POST[‘bannercode’]);
$sqlquery=”UPDATE “.$tablename.” SET `enabled` = 1 , `enabled_time` = CURRENT_TIMESTAMP WHERE `wp_ad_rotation`.`id` =”. $_POST[‘id’].”;”;
$success=$wpdb->query(“$sqlquery”);

if($success===false){
echo ‘Error saving banner’ ;
}
}

if (array_key_exists ( ‘delete’, $_POST )) {
global $wpdb;

$sqlquery=”DELETE FROM “.$tablename.” WHERE `wp_ad_rotation`.`id` =”. $_POST[‘id’].”;”;
$success=$wpdb->query(“$sqlquery”);

if($success===false){
echo ‘Error saving banner’ ;
}
}

$banners=self::ad_get_banners();
$totalbanners=count($banners);
echo “total banners $totalbanners”;

?>

Add a banner tag here
ID:
Banner Name
Banner Type Web User interface
Popup

Banner size

330 square
728 leader board
automatic

Banner tag code

Now we have the admin menu ready. just need to start work on widget

form (insert/display meta)
update (save)
widget (display content to user UI)