How to Create a WordPress Plugin

Plugins are ways to extend and add to the functionality that already exists in WordPress. We don’t have to be a dedicated plugin developer to write WordPress plugin. There are situation where we need to alter some existing functions, or add some features to existing site. You may learn from various resources that, to add this, you need to drop code snippet to function.php. The fact is, making changes to function.php isn’t always the best solution.

Comparing with adding customization to function.php, adding custom code via WordPress plugin can do the same and much safer. You can disable a plugin easily in case things go wrong. WordPress is very flexible, and easy to work with. Adding our own plugin is pretty simple to start and straightforward.

 

Standard Plugin File

A plugin must contain a standard header to be handled & accepted by WordPress. Here is the example:

<?php
/**
 * Plugin Name: Name Of The Plugin
 * Plugin URI: http://URI_Of_Page_Describing_Plugin_and_Updates
 * Description: A brief description of the Plugin.
 * Version: The Plugin's Version Number, e.g.: 1.0
 * Author: Name Of The Plugin Author
 * Author URI: http://URI_Of_The_Plugin_Author
 * License: A "Slug" license name e.g. GPL2
 */

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

// Custom code goes here

 

Few things to know:

  • Plugin name
    Each plugin goes into a WordPress installation should have a unique name to avoid name conflict. For example, instead of “My Custom Plugin”, I normally use “Custom Plugin for XYZ.COM”.
  • Plugin Files
    It is recommended to name the main plugin PHP file derived from plugin name. Although plugin file name don’t necessarily to be unique, it is a good practice to do so.
  • Plugin Folder
    Plugin folder must be unique. The easy way is to name the folder following the main plugin PHP file name. For example: “custom-plugin-for-xyz-com”.

Following this standard, and create a custom plugin for the project you work on. You can start adding custom features to WordPress. (Remember to activate it.)

Function.php vs Custom Plugin

General rule, add custom code to function.php if the function / feature is theme related; and leave theme independent customization to custom plugin. Honestly, this is all just personal preference. Because anything that exists in function.php can exist in plugin. I usually don’t alter function.php no matter what, but add changes in my custom plugin. Mainly, because I work mostly on existing site either troubleshooting or adding features, separating my custom work with existing code is overall a good practice.