According to W3Techs, WordPress powers 39.1% of all websites in 2020. This is because WordPress has a ton of built-in functionalities, but also because it is highly customizable through plugins. Plugins are a critical component of the WordPress platform, allowing you to easily extend functionality that goes beyond the WordPress core, without modifying it.
For example, WooCommerce converts your WordPress site into an eCommerce store, enabling you to sell products and services to your clients through the web. Yoast SEO is a plugin that helps you manage your SEO to rank your posts higher on search engines.
While developers can list their plugins on the web for anyone to use, these plugins may not solve your specific requirements. There are almost sixty thousand plugins on the official WordPress plugin directory, which means you should check if an existing plugin matches your requirements, before building your own. If there isn’t one that matches your needs, you should consider creating a custom WordPress plugin.
In the background, scripting and query languages like PHP and SQL power WordPress. Therefore, expertise in these technologies, as well as experience with deployment, are necessary to create a WordPress plugin.
In this tutorial, we will guide you through the creation of your first plugin.
WordPress Plugin Development: Basic Concepts
When WordPress gets updated to a new version, it overrides its core files. Because of this, if you add a custom functionality to a WordPress site by directly modifying the WordPress core, your changes will be wiped out upon WordPress upgrade. This leads to one of the core WordPress development concepts – any functionality you want to add or modify should be done using plugins.
A WordPress plugin is essentially one or more functions defined in PHP files, as PHP is the main scripting language powering WordPress. It also typically has 3 other components: hooks (action hooks and filter hooks), shortcodes and widgets. These are the main elements of WordPress plugin development.
Hooks
Hooks are features in WordPress that allow you to manipulate a process at a specific point without changing WordPress core files. Therefore, hooks provide a way for your plugin to attach to the working of WordPress core. You can associate code snippets or functions with hooks to execute at various points in time. A hook can be applied both to action (action hook) and filter (filter hook).
Before we dive in, let’s quickly cover a few differences between these two:
An action is a process in WordPress. An action hook allows you to add a process. You can work with action using the add_action() function in WordPress. Common examples of actions are creating, reading, or saving a post in WordPress. You can associate PHP functions or code snippets with actions. You can even create your own action and associate code with it. An action enables you to add functionality to a plugin.
You can hook on to an action and run your custom functionality. For instance, you can associate your function, custom_function() to the action of saving a post. You should use the add_action() function as shown below.
function custom_function( $post_id ) {
//do something
}
add_action( 'save_post','custom_function' );
This code snippet ensures that every time WordPress saves a post, the function, custom_function(), will run.
A filter is a hook that modifies a process. Filters help in manipulating existing data, without the need to alter its source. You can use the apply_filters() function to use a filter hook. It takes two required arguments – the name of the filter and the value that will be filtered.
echo apply_filters( 'filter_name','filter_variable' );
Further, you can use the add_filter() function to create a custom filter. You define the name of the filter you want to call, along with the function that will be called to modify the filter.
function modify_value( $filter ) {
//change $filter and return new value
}
add_filter( 'original_filter','modify_value' );
Shortcodes
When you develop a plugin, it does not directly have access to the WordPress theme. To communicate with the WordPress theme and display some information to the user, you need to use a shortcode. Shortcodes allow users to insert a dynamic HTML element into a post or a page.
Here is an example of a shortcode which adds the text “Hello World” to your post.
//Register shortcode
add_shortcode( 'hello_world_shortcode','hello_world_output' );
//define function to show output
function hello_world_output( $atts, $content = '', $tag ){
$html = '';
$html .= 'Hello World';
return $html;
}
Widgets
Widgets provide developers another way to display your plugin’s content to the end-user. WordPress has a WP_widget class in PHP, that you need to extend to create a widget for your plugin.
Now that we covered the basic concepts of WordPress plugin development, let’s explore the key steps in creating a custom plugin.
WordPress Plugin Development: Key Steps
Step 1 – Define the Requirements
The first step in WordPress plugin development is to clearly define your development needs. Before you start, ensure that you have a clear idea of the objective of the plugin. When you have an accurate picture of the issue to resolve, you are able to execute your idea into an efficient plugin.
There are many factors that you can consider in this step. What are the features of this plugin? How are you going to customize it? What will the design look like?
Make sure to answer these questions because this step is linked to all the other steps of the process.
In this specific example, we are going to create a Hello World plugin. We will use this simple, bare-bones plugin as an example to illustrate the steps that you should follow to create a WordPress plugin.
Step 2 – Create a WordPress Plugin Directory Structure
The default WP directory for storing plugin code in the back end is /wp-content/plugins/. How you structure your plugin within this directory will depend on the complexity of the plugin. The name of the directory is the same as your plugin name, in lowercase and dashes in place of spaces.
We recommend having a single PHP file that contains all the code of the plugin (/wp-content/plugins/my-plugin/my-plugin.php). Such a structure is ideal for a simple plugin that serves a small function.
If you plan to work with a plugin that has a lot of assets, you can organize your plugin based on the function of the code and PHP files. You can create directories such as assets for CSS and JavaScript files, i18n for localization files, templates, and widgets.
For more complex plugins, you can create an MVC view, with directories for model, view, and controller within the my-plugin directory. This helps in debugging later in a shorter time. In our simple and straightforward example of the Hello World plugin, we will create the hello-world directory with a single PHP file, hello-world.php inside it.
Step 3 – Configure your Plugin
Once you create your plugin directory and add files within it, you then need to add the file header. The file header is a PHP comment block that contains information about the plugin. You can find the contents of a sample file header in the WordPress codex.
After adding the file header, it will appear in the list of plugins on your WordPress admin.
The following lines constitute the plugin headers and go to the top of the plugin file.
<?php
/**
* Hello World
*
* @package HelloWorld
* @author Your Name
* @copyright 2020 Your Name
* @license GPL-2.0-or-later
*
* @wordpress-plugin
* Plugin Name: Hello World
* Plugin URI: https://mysite.com/hello-world
* Description: Prints "Hello World" in WordPress admin.
* Version: 0.0.1
* Author: Your Name
* Author URI: https://mysite.com
* Text Domain: hello-world
* License: GPL v2 or later
* License URI: http://www.gnu.org/licenses/gpl-2.0.txt */
...
?>
Step 4 – Add Functionality to your Plugin
While you have created an empty plugin, it does not accomplish anything yet. You need to add functionality to it now. The plugin handbook of WordPress should serve as a guide. This is the step where you bring your idea to life.
In our simple plugin example, we will create a WordPress admin page with the text “Hello World” in it. When you add an admin page, it also adds a menu item.
<?php
function print_hello_world_title() {
echo "<h1>Hello World</h1>";
}
function hello_world_admin_menu() {
add_menu_page(
'Hello World',// page title
'Hello World Menu Title,// menu title
'manage_options',// capability
'hello-world',// menu slug
'print_hello_world_title' // callback function
);
}
add_action( 'admin_menu', 'hello_world_admin_menu' );
...
?>
The code snippet above adds a menu item using the action hook admin_menu
and executes the function hello_world_admin_menu
. In the function, we use the inbuilt function add_menu_page(), which adds a menu item and a page for the plugin on WordPress admin. We add the page title, menu title, capability, menu slug, and a callback function. We define the page contents in the callback function, where we just print the header “Hello World”.
Step 5 – Package your Plugin
A developer often works on a WordPress plugin in a development environment. To shift the plugin to your production site, you would need to compress the plugin directory and upload the zipped plugin file to WordPress Admin.
WordPress Plugin Development: Best Practices
- You can quickly get into WordPress plugin development by using the right tools. A text editor that you are comfortable with, an FTP client to quickly shift files between your local machine and the server, and a development server to test your plugin on the server help you in creating your plugin through quick iterations.
- Creating a plugin from scratch requires a lot of time and effort. While there is no standard process for creating a plugin, you can opt for plugin development through a boilerplate. Using a boilerplate saves a lot of time by reusing code.
- While developing a plugin, use the inbuilt-functions features of WordPress whenever possible to avoid rework and shorten web development time. Adhere to WordPress coding standards while developing your plugin.
- Use MVC structure to ensure a consistent structure for others to add to your plugin conveniently at a later stage.
- Update your plugin to ensure compliance with the latest versions of PHP and WordPress. This keeps your website safe from security risks.
Bonus tips from Codeable plugin development experts
Expert WordPress plugin developers Bishoy A and Joseph Gabito advise:
Always sanitize and escape data
When writing a plugin, it’s very important to secure the output of your plugin by using the appropriate WordPress data sanitization functions. Failing to do so puts your plugin and your whole website at a risk of hacking. Let’s take the following PHP statement as an example:
echo $my_custom_variable
Written this way, it allows intruders to put some custom JavaScript or MySQL code to it which can then lead to XSS and/or MySQL injection attacks. That’s why you want to use the built-in security function esc_html and instead write:
echo esc_html( $my_custom_variable )
Esc_html function just like its name suggests, escapes all HTML and JavaScript codes in your variable, making it more secure. There are a lot of similarly used functions, refer to the WordPress Codex for documentation about all functions.
Use WPDB whenever possible
When you start writing a plugin that does custom CRUD operations (Create, Read, Update, Delete) in the database, it is strongly advised to use the WordPress database abstraction class called wpdb.
There are a lot of advantages to using WPDB. One of the most important benefits is security. Instead of writing your methods to secure your queries, wpdb already provides built-in security methods to protect your queries from database hacks such as $wpdb->prepare.
Additionally, $wpdb class can potentially save you a lot of time.
Always consider internationalization (i11n) and make your plugin easily translatable
Internationalization is the process of developing your plugin in a way that it can easily be translated into other languages. For example, a “Save” button coded like this wouldn’t support i11n.
<button id=”exampleButton”>Save</button>
Instead, it has to be coded like this to ensure it is translatable:
<button id=”exampleButton”><?php _e( ‘Save’, ‘text_domain’ ); ?></button>
To ensure you’re doing i11n right, follow the official WordPress Internationalization documentation.
Prefix functions and add a namespace to Class
When writing a plugin for the first time, you may be tempted to write a function like the following:
function get_data() {
// do something...
}
While this might work for you when working on your local development environment, the chances of naming collision with other plugins will be very high since there might be some plugins installed in your wp site using the same function name, thus producing a PHP Fatal Error.
To solve this problem, developers are advised to prefix their functions. For example, instead of writing get_data (), you’ll change the name of the function from get_data() to your_prefix_get_data().
Change your_prefix to match the directory name of your plugin or text-domain. In our example, we’ll use hello_world _get_data().
Additionally, you may want to make sure there are no existing functions that calls on the same function name, so you can do something like:
if ( ! function_exists(“hello_world_get_data”) ) {
function hello_world_get_data() {
// do something...
}
}
This method does not only prevent a naming collision but also makes your function overwritable via Theme or Child Theme.
Final Thoughts on WordPress Plugin Development
In this tutorial on WordPress plugin development, we explored how you can create a plugin from scratch. While it requires technical expertise and patience, you can achieve your goal of launching a plugin with the relevant knowledge, skills, best practices, and the willingness to get your hands dirty. However, if you don’t have any foundational skills and limited time to learn the basics yourself, you can consider working with a professional WordPress developer specializing in custom plugin development.
Plugin development and customization are some of the most popular services that our vetted experts offer on Codeable.
Frequently Asked Questions
How to learn WordPress plugin development?
There are thousands of great tutorials and video courses online, but we would recommend going through and familiarizing yourself with the official WordPress documentation first.
The official Plugin development handbook
What are the benefits of WordPress plugins?
Plugins enhance the functionality of your WordPress site. We create plugins to ensure that we do not change WordPress core, which is overwritten with every WordPress update.
Do I need to create a new plugin for my website?
It depends. There are already thousands of existing plugins that you should check out. If you don’t find the right plugin for you, consider creating one that suits your needs.
Where are WordPress plugins stored?
Any WordPress plugin that you download and install on your site is stored in the directory /wp-content/plugins/. Consequently, any plugin that you create should also be stored in the same directory.
What skills do I need to start with WordPress plugin development?
To create a WordPress plugin, you should have a solid understanding of the core technologies that power WordPress: HTML/CSS, JavaScript for the front end, and PHP, SQL for the back end.
How do I publish my plugin to the WordPress plugin directory?
If your plugin adheres to the requirements and guidelines for a WordPress plugin, you can publish it on the WordPress plugin directory through these simple steps.
How can I uninstall my plugin?
The easiest way to permanently remove a plugin is to deactivate it and remove the plugin directory. Additionally, you can explore the uninstall hook to automate the uninstallation process.
I do not have the skills to develop a plugin? How should I proceed?
If you are new to WordPress plugin development with limited coding experience, you should try and get your hands dirty with a small-scope plugin. However, if you need a more complex plugin, you may consider working with an experienced developer through Codeable.