Published Tuesday 1st April 2014

Wordpress plugins tutorial

This week's tutorial covers Wordpress plugins. Wordpress is an out of the box development environment which was originally used as a blogging and CMS system but has evolved into much more. The system, with its extensive but easy to use plugins, can cover anything from duplicating posts to a full blown e-commerce system. This tutorial will teach you how to develop your own plugin, using a combination of hooks, scripting, HTML, CSS and images. A plugin is actually relatively easy to develop once you understand how the hooks work.

A hook is the equivalent to an event but it is called by the code rather than by a user. One developer will put hooks in place and then call them at points in the code. To develop your first plugin, assuming you've installed WP, open up wp-content/plugins and create a new folder with your plugin name. Then create a .php file inside this folder with again the name of your plugin (e.g. my-plugin.php). Then at the top of this file, after the <?php opening tag, put the following:

/*
Plugin Name: Your Plugin Name
Description: A short Description
Version: 1.0
Author: You
*/

Next you'll probably want to create some folders within your plugin. I normally create css, images, libraries, front-end and admin. CSS and images are self explanatory, libraries holds any PHP libraries I may want to include (e.g. PHPMailer), front-end is for anything that will be shown to users, and admin is anything that will be shown to administrators in the WP admin. Next you'll want to define some variables and possibly include some libraries, such as these below:

/********************************
* LIBRARIES & INSTANCE VARS
*********************************/
$pluginDir = dirname(__FILE__);
$srcDir = plugins_url('', __FILE__);
//include($pluginDir . '/libraries/yourLibrary.php');

$pluginDir can be used for including (see examples below). The $srcDir can be used for images, e.g. <img src="<?php echo $srcDir; ?>"/images/yourImage.png" alt="Your Image" />

Next I put my hooks. Wordpress hooks can be called, or a developer can make an action which then can be called in the theme code (explained later on). To call a hook you simply do: add_action('hookName','yourFunction');. All hooks can be seen here: http://codex.wordpress.org/Plugin_API/Hooks (you'll probably want the action hooks). Here are some examples of hooks:

/********************************
* HOOKS
*********************************/
add_action('init','settings_submits');
add_action('init','scores_css');
add_action('init','scores_googleChartsAPI');
add_action('admin_init','scores_admin_css');
add_action('save_post', 'save_scores' );

So what exactly is this doing? Well on WP initiation (regardless of whether the user is on the front end or in the admin) it will run the functions: settings_submits, scores_css and scores_googleChartsAPI. On admin initiation it will run the function: scores_admin_css. On saving a post in the administation area it will run the function: save_scores. These functions have been stripped down and can be seen here:

/********************************
* = FUNCTIONS =
*********************************/
/********************************
* == ADMIN ==
*********************************/
/********************************
* USED IN ADMIN WHEN A POST IS SAVED
*********************************/
function save_scores(){
	if(isset($_POST['frmSlides'])){
		global $customDB;
		$post = get_post();
		$cUser = wp_get_current_user();
		$data['fldResponse'] = serialize($_POST['fldSlide']);
		$data['fldReview'] = serialize($_POST['fldReview']);
		$data['fldStatus'] = 'approved';
		$data['fldType'] = 'Review';
		$data['fldUser'] = $cUser->data->ID;
		$data['fldProduct'] = $post->ID;
		$customDB->setTable('plugin_scores');
		$res = $customDB->fQuery('
			SELECT fldId FROM plugin_scores 
			WHERE fldProduct = \''.$post->ID.'\' 
			AND fldType = \'AdminReview\'
		');
		if(empty($res)){
			$customDB->insert($data);
		} else {
			$customDB->update($res['fldId'], $data);
		}
		//$customDB->debug(); $customDB->getValidErrors(true); die;
	}
}
function scores_admin_css() {
	wp_register_style('score_admin_style', plugins_url('css/admin-style.css',__FILE__));
	wp_enqueue_style('score_admin_style');
}
/********************************
* == FRONT END ==
*********************************/
/********************************
* SUBMITS - FRONT END
*********************************/
function settings_submits(){
	if(!empty($_POST)){
		//USER SUBMITTED FORM
		global $customDB;
		$cUser = wp_get_current_user();
		if(isset($_POST['frmHaveHadSlides'])){
			//Setup data
			$data = $_POST;
			$data['fldResponse'] = serialize($_POST['fldSlide']);
			$data['fldType'] = 'UserReview';
			$data['fldUser'] = $cUser->data->ID;
			$data['fldCriteria'] = $_POST['fldCriteriaId'];
			$customDB->setTable('plugin_scores');
			//Check to see whether to insert or update
			$res = $customDB->fQuery('
				SELECT fldId FROM plugin_scores 
				WHERE fldProduct = \''.$customDB->escape($_POST['fldProduct']).'\' 
				AND fldUser = \''.$cUser->data->ID.'\' 
				AND fldType = \'UserReview\'
			');
			//Insert or update
			if(empty($res)){
				$customDB->insert($data);
				$type = 'added';
			} else {
				$customDB->update($res['fldId'], $data);
				$type = 'updated';
			}
			//Redirect
			$_SESSION['notifications']['success'] = 'Successfully ' . $type . ' review';
			header('Location: ' . $_SERVER['REQUEST_URI']);
			exit;
			//$customDB->debug(); $customDB->getValidErrors(true); die;
		}
        }
}
function scores_googleChartsAPI(){
	wp_deregister_script('googleChartsAPI');
	wp_register_script('googleChartsAPI', "http" . ($_SERVER['SERVER_PORT'] == 443 ? "s" : "") . "://www.google.com/jsapi", array(), null);
	wp_enqueue_script('googleChartsAPI');
}
function scores_css() {
	wp_register_style('score_style', plugins_url('css/style.css',__FILE__));
	wp_enqueue_style('score_style');
}

You can include HTML code via includes within your functions. The functions above do not have any HTML output but an example would be: include($pluginDir . '/front-end/scores.php'); within your function.

The final thing to note is you can also call your own defined hooks within your theme's code (i.e. wp-content/theme/[YOUR_THEME]/[YOUR_FILE].php). This can be done by first adding an action and then using do_action. So in your plugin you would do: add_action('output_scores', 'outputScores'); and then within your theme file you would do: do_action('output_scores');. That would run the function outputScores which is within your plugin.

Hopefully all this should be enough to develop your own Wordpress plugin. Please feel free to leave comments expanding upon anything I may have missed, or suggest improvements.

Photo of Steven

Steven

Steven is a former QWeb Ltd director and continues to work with us as a contract developer. He's experienced with a number of front-end technologies but is primarily focussed on back-end development, particularly building complicated plugins and bespoke mechanisms for Wordpress.

Blog posts are written by individuals and do not necessarily depict the opinions or beliefs of QWeb Ltd or its current employees. Any information provided here might be biased or subjective, and might become out of date.

Discuss this post

Nobody has commented yet.

Leave a comment

Your email address is used to notify you of new comments to this thread, and also to pull your Gravatar image. Your name, email address, and message are stored as encrypted text. You won't be added to any mailing list, and your details won't be shared with any third party.

This site is protected by reCAPTCHA and the Google Privacy Policy & Terms of Service apply.