WordPress Plugin Developer CMS frameworks are a must-have in the skill set of every web developer. They are powerful, flexible and customizable. With a powerful CMS such as WordPress, you can create a very flexible and versatile website with just a little effort. The main strengths of WordPress as a CMS is its structure which involves plugins and themes. There are a lot of plugins for different functionality and themes for enhancing the look of ones website which are available on WordPress.org and other third party sites which offer customized themes and plugins.

As a WordPress developer, you develop themes and plugins everyday. WordPress plugin development is fun to learn and comes with a ton of benefits for the developer. You can easily tweak a site and earn good income as a WordPress developer. In this article we look at some of the most important things to know about developing WordPress plugins. This assumes that the reader has some knowledge of the WordPress CMS.

1. Creating a Plugin

In order to create a custom WordPress plugin, one must create a folder where the plugins created will be placed. All the plugin files created should be placed inside that folder. The plugin should also have its own main file. The naming for the plugin files should be in simple letters with hyphens (-) for separating words. For example, a typical filename for a slider could be my-custom-plugin.php. Inside the main file you should have a comment which will allow WordPress to identify your plugin.

The comment structure is as follows:

<?php
/*
Plugin Name: Sample Name
Plugin URI: https://www.chrsinteractive.com/
Description: Advanced SEO options for your WordPress website
Version: 1.0
Author URI: https://www.chrsinteractive.com
Author: CHRS Interactive
License: GPL2
*/ 

2. Activating and Deactivating a plugin

In order to activate a plugin, simply click on the activation link where the plugins are listed. Simple plugins do not require much in terms of activation. However, more advanced plugins require various functionalities such as creating plugin tables, initializing the plugiin options and so on. Let us look at the details of activating and deactivating plugins.

Plugin Activation Hook

The WordPress CMS has a function known as register_activation_hook which is usually executed upon activation of the plugin. You can always add some other functionality to the activation sequence using the method below

function wp_sample_activation() {
}
register_activation_hook(__FILE__, 'wp_sample_activation');

You needs to include the the path to the file containing the function for activation as the first property and the name of the function as the second property. In case the function to be executed on activation is in the main file for the plugin you can use _FILE_. Tasks that can be done upon activation include creation of tables, data validation, and initializations.

Plugin Deactivation Hook

Plugin deactivation can be easily handled by using the register_deactivation_hook which uses a similar format to the activation hook. Tasks that can be accomplished inside the function for deactivation include cleaning up of resources and options, and closing tables.

function wp_sample_deactivation() {
}
register_deactivation_hook(__FILE__, 'wp_sample_deactivation'); 

3. Creating Custom Tables

The structure of the database table in WordPress is extremely flexible and you can easily build your own custom functionality using the tables that are available. However, in some situations, you may want to integrate more complex systems such as booking systems, shopping carts and other systems. In such situations, it is important to identify situations that require custom tables. In order to do this, look at the available table options and try to work with them to store the project data. In case they are not sufficient, you can create your own custom tables by simply using the method below.

global $wpdb;
$wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}sample_table");
$sql1 = "CREATE TABLE {$wpdb->prefix}sample_table ( id int(11) NOT NULL AUTO_INCREMENT,
                                                       activation_code varchar(255) NOT NULL,
                                                       email varchar(75) NOT NULL,
                                                       status int(11) NOT NULL, PRIMARY KEY  (id) )
         ENGINE=InnoDB AUTO_INCREMENT=1;";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql1);

4. Including Styles and Scripts

Although scripts and styles can be echoed everywhere, the recommended way is to use the wp_enqueue_script function to add scripts. This will check if the script files are available and takes care of dependency with other scripts. The code below shows an example of a typical use of wp_enque_script.

add_action('wp_enqueue_scripts', 'sample_scripts');
function sample_scripts() {
  wp_enqueue_script('jquery');
  wp_register_style('sample_style', plugins_url('styles.css', __FILE__));
  wp_enqueue_style('sample_style');
  wp_register_script('jqueryUICore', plugins_url('ui/jquery.ui.core.js', __FILE__),array("jQuery"));
  wp_enqueue_script('jqueryUICore');
  $config_array = array("sample_name"=>"sample_value"]);
  wp_localize_script('jqueryUICore', 'sampleData', $config_array);
}

Registration of the style file can be done using wp_register_file and in order to have the file in the plugin simply use wp_enqueue_style. You have to provide a unique identifier for the file containing the style and a path to it. If a script is dependent on other scripts, it can be mentioned as the third property. Additional usage data can be added to the script by using wp_localize_script function.

5. Creating Shortcodes

Shortcodes are predefined blocks of codes that you can use anywhere. This is important for a maintainable code base and to avoid code rewriting by reusing it. This is important in order to add dynamic behavior to pages which call the shortcodes. Shortcodes are created in the following format.

add_shortcode("shortcode_name", "shortcode_function");
function shortcode_function() {
  return "<input type='button' value='Share' /> ";
}

6. Content Filtering

When developing a plugin for a blog, it is important to include a capability for filtering post or page content on the blog. For example:

function sample_content_filter($content) {
  $banners = "HTML for banners";
  $author = "HTML for author info";
  return $banners.$content.$author;
}
add_filter( 'the_content', 'sample_content_filter' );

Each time a post or a page page is being viewed, the content will be passed to the above function and you can modify, add or remove content with the code above.

WordPress conditional tags are used to filter content in specific pages. For instance, you can use the following code to to filter the content on a post detail page.

function sample_content_filter($content) {
  if(is_single()){
  return $banners.$content.$author;
  }
}

7. Working with Ajax

Ajax is used to make a web page more interactive. A WordPress developer should have a working knowledge of Ajax. jQuery’s Ajax functionality looks like this.

$.post("admin-ajax.php", { action:"sample_ajax_action" },
function(result, textStatus) {
}, "json");

The most important part of a request in Ajax is the action. This is used in the WordPress code in order to easily identify the request. Another important fact to keep in mind is that all ajax requests should pass through the admin-ajax.php file.

function sample_ajax_action() {
echo json_encode($your_result_array); exit;
}
add_action('wp_ajax_nopriv_sample_ajax_action', 'sample_ajax_action');
add_action('wp_ajax_sample_ajax_action', 'sample_ajax_action');

8. Writing SQL Queries

In WordPress development, one has to consider security of queries made to the database in order to avoid web application attacks in the form of SQL injection. Cleaning data that is submitted to the system by the user for SQL injection can be done using the prepare method. This is done using the code below.

$wpdb->query($wpdb->prepare("update wp_sample_table set status=1 where activation_code=%s and status=%d",$activationCode,$status));

You should always filter the data before executing the SQL query by assigning escape characters to the SQL and variable values at the end.

9. Adding Option Boxes

There is a number of fields that are included in WordPress by default. These include the content, title, excerpt and image. In order to include additional behavior a WordPress developer needs to add custom fields section. The section for custom fields only includes text boxes so you need to include separate fields if you need to have drop downs, option buttons, check boxes and so on. This can be accomplished easily as shown below.

add_action('add_meta_boxes', 'add_custom_fields_box');
function add_custom_fields_box() {
  add_meta_box('custom_fields_box_id', 'Custom Info', 'display_custom_info_box', 'post', 'normal', 'high');
}
function display_custom_info_box() {
global $post;
$html = "<table><tr><td>Custom Checkbox</td><td><input id='custom_checkbox' type='checkbox' name='custom_checkbox'  /></td></tr> <tr><td>Custom Selecy</td><td><select name='custom_select'  > <option>Option 1</option> </select></td></tr> <tr><td>Custom Upload</td><td><input id='custom_file' type='file' name='custom_file'  /></td></tr></table>";
echo $html;
} 

Custom fields are saved in the wp_options table with all the necessary values associated with them. Optional field names should begin with an underscore in order to avoid duplication with the custom fields section.

10. Using Nonces for Security of Plugins

When developing WordPress plugins, security is a major concern since the WordPress ecosystem is huge with a diverse variety of people with different intentions. Data that is submitted by a user using a form should never be trusted and thus it should always be validated and cleaned before being executed.
WordPress provides a concept called a nonce which creates a nonce value, or arbitrary number used only once, when a form is generated
WordPress has the concept called a nonce which creates an arbitrary number or nonce value, when a form is generated. The nonce value can only be used once and is generated using code below.

wp_nonce_field('sample_frm_nonce', 'sample_frm_nonce');

The first parameter is used as a unique identifier while the second one is used as a hidden name for the form field. Once the user has submitted the form, the nonce value can be validated using the code shown below.

if (!isset($_POST['sample_frm_nonce']) || !wp_verify_nonce($_POST['sample_frm_nonce'], 'sample_frm_nonce')){
  return;
} 

In case of an invalid nonce value, the request will not be processed any further.

In conclusion, the above mentioned things are some of the most important ones for plugin creation. However, they are just a tip of the iceberg and one is advised to learn more in order to be a better WordPress developer.

Ready to discuss your project?

Choose CHRS Interactive, a Los Angeles Wordpress Design agency to forge your online presence. We would love to discuss being your new partner. Please contact us or give us a call at 818-568-4798.