DEV Community 👩‍💻👨‍💻

Cover image for How to create your first WordPress plugin

Posted on • Updated on

How to create your first WordPress plugin

A good practical knowledge of WordPress, HTML, CSS, JavaScript, and PHP is often crucial if you want to create a WordPress plugin. This is not strange, especially if you are developing a WordPress plugin for commercial purposes. At this stage, you’re no longer fiddling with your personal website, but that of many others which requires high safety measures.

However, every expert was once a newbie. And creating your first WordPress plugin is not only a giant step towards mastering the aforementioned programs. But a means of discovering many WordPress plugin projects you can take on.

This article will provide an easy step-by-step guide on how to create your first WordPress plugin from scratch. In the first section, you’ll learn about WordPress plugin, the basics for WordPress plugin development, and WordPress plugin development environment. The final section of this piece will first explain the WordPress plugin API before putting the process of creating a WordPress plugin into practice by providing steps on how to create a simple coming soon/maintenance page plugin.

Table of Contents

1.1 What is a WordPress Plugin?
1.2 Basics for WordPress plugin development
1.2.1 Naming convention
1.2.2 Plugin safety Basic methods for securing your WordPress plugin
1.2.3 Plugin structuring
1.2.4 WordPress’ coding standards
1.3 Environments for creating a WordPress plugin
1.3.1 On WordPress core environment
1.3.2 Off WordPress core environment
2.1 WordPress plugin API: hooks, actions, and filters
2.2 Creating a coming soon page WordPress plugin
2.2.1 Features of the plugin
2.2.2 Creating the plugin folders
2.2.3 Creating the main PHP file
2.2.4 Creating the coming soon template
2.2.5 Creating the CSS and JavaScript
2.2.6 Including the JavaScript
2.3 Conclusion

1.1 What is a WordPress plugin?

WordPress plugin is a software comprising of different functions that can be used to extend the standard features of a WordPress website without altering the core WordPress files. It is simply a conglomerate of PHP scripts that can be added to your WordPress website to introduce new functions or tweak the existing functionalities. Using a WordPress plugin, you can remove unwanted WordPress behaviors or modify them to suit your needs.

Plugins allow you to interact with WordPress core easily with very little or no risks. They are not overwritten or automatically deleted when you update your WordPress core. And you can simply deactivate your plugin through the Admin Control Panel if there’s an error in your coding. Sometimes, WordPress will automatically deactivate a plugin if it has a serious error. This allows you to continue using the existing website functionalities until you can fix the plugin error.

You may be wondering why WordPress cannot simply integrate all the important plugins into the CMS’s core in subsequent updates since they are useful. Well, this is to uphold its user-friendliness by ensuring that irrelevant functionalities are not embedded into anyone’s WordPress installation. According to the WordPress philosophy, features not used by 80 percent of all users would not be included in the core, but exist as plugins.

1.2 Basics for WordPress plugin development

There are basic rules for creating a plugin or any add-on in WordPress that every developer must adhere to, including amateurs and experts. This is to ensure compatibility and avoid some of the potential problems with contributing scripts to already existing programs. You are required to carefully review the recommended WordPress best practices for developers if you intend to explore more into WordPress plugin development.

1.2.1 Naming convention for your classes, variables, and functions

When creating the PHP scripts of your plugin, you must consider how you want to name your variables, functions, classes or even your plugin to avoid naming collision. The introduction of a new function with an already existing function name is not what you want to do. Your function could potentially override those existing in another plugin or WordPress core itself.

The best way to overcome this challenge is to prefix every name with a unique set of characters, usually the initials of your plugin name. Another WordPress-recommended method, widely used by most developers, is to declare all your functions inside a class.

Here is an example. Assuming that your plugin name is Coming Soon Page, using a prefix in your functions could be:

                 function CSP_maintenance_mode () {}
Enter fullscreen mode Exit fullscreen mode

Your class name must have the unique characters to still distinguish it from other classes in your WordPress if you’re declaring all functions inside them.

         class CSP_menu {  
           static function maintenance_mode () {  
Enter fullscreen mode Exit fullscreen mode

However, you may want to verify if that the name you want to use hasn’t already been taken, for both classes and functions by passing them through a check before declaring them.

       if ( !function_exists( 'CSP_maintenance_mode' ) ) {  
            function CSP_maintenance_mode () {  
Enter fullscreen mode Exit fullscreen mode

The same procedure is used in declaring a class, with the word class replacing function in the example above.

Also, having a unique name for your plugin is a must to avoid conflict with other preexisting WordPress plugins. You may have to check the official WordPress plugin repository to ensure that your choice of name is unique.

1.2.2 Plugin safety

It’s clear enough that your first WordPress plugin would end up on your personal website. What if you wish to distribute them? Let’s assume you could tolerate any safety risks. You must consider all the safety measures in building a WordPress plugin if you plan to include them in the WordPress plugin repository or you’re distributing it privately to a company. Plugins are one of the major roots hackers usually want to explore while trying to gain access to a website. And if an insecure plugin on the website has access to the WordPress database, it becomes easy to access. The website owner’s information could be at a high risk of being compromised.

You must ensure that your plugin does not help in spreading illegal or unwanted data. This could be done by applying filters to the user’s input, shutting down queries that could potentially help to inject attacks on the website SQL, etc. Another stability requirement is to ensure that the appropriate authority has access to the plugin folder. And how can you achieve that? Basic methods for securing your WordPress plugin

There are two security measures you can apply to ensure that your plugin files are only accessed by the appropriate authority. These two approaches are very important when creating a WordPress plugin.

The first approach is to create an empty file called index.php inside your installation folder. This is in case a user or an administrator gains access to your plugin folder directly from a browser. And because every browser first loads the index file of every URL, you take a precautionary measure by automatically directing the user to the only file you want them to access, which will be index.php. You don’t want the folder to return all your plugin files.

We often include a commented out PHP comment in the file:

    //Silence is golden.  
Enter fullscreen mode Exit fullscreen mode

This will display an empty page to anyone trying to access the plugin folder through the wp-content folder link, like the following:

The second approach is to confirm the existence of a constant function or global variable during the execution of your plugin. This is so you don’t expose a massive vulnerability of access to your website through the plugin. The most common constant variables used in this security check is the absolute path (ABSPATH) defined by WordPress when you initialize the CMS. This should be the first line of code in your plugin’s main php file.

    if ( ! defined( ABSPATH ) ) {  
Enter fullscreen mode Exit fullscreen mode

The code is simply commanding your plugin to close (die or exit) if the constant variable ‘ABSPATH’ is not defined. You may choose to swap the keyword die with exit since they mean the same thing. See WordPress plugin handbook for more on security.

1.2.3 Plugin structuring

It’s important to structure your plugin in a manner that would allow other developers to understand how your plugin works. You want to consider the number of files that could be in your plugin, and the folders to save them. We’ll see an example when we’re creating a simple plugin later in this article.

1.2.4 WordPress’ coding standards

While you have a plain understanding of HTML, PHP, CSS, and JavaScript, WordPress expects you to code them in a certain manner. The essence is to improve the readability of your code while also avoiding common coding errors. Some of the WordPress coding standards you must familiarize with include ensuring that all tags (HTML) are closed and with a single space before the slash, understanding the preferred case for all attributes, required indentation, quotes, how to properly call functions, etc.

1.3 WordPress plugin development environment

Of course, you can use any IDE of your choice, provided they are resourceful and help to keep you away from errors. But the next thing you want to consider is where to keep your plugin folders during the development. You may want to be testing every code immediately as you write them to track errors and progress by creating the plugin inside your WordPress installation folder (on WordPress core) or develop the plugin in a different folder (off WordPress core) and install each time you want to test the plugin.

1.3.1 On WordPress core environment

Creating your plugin inside a WordPress installation folder allows you to see instant results of every change you implement in your code each time you deactivate and reactivate the plugin. This is the easiest way to successfully create a WordPress plugin without going through several heartbreaking rounds of debugging process.

However, you want to perform this on a locally hosted WordPress website. Follow the steps below to set up on the WordPress core plugin development environment.

  1. First, go to the root folder of your WordPress installation folder and open the wp-config.php file
  2. Scroll down to the ‘WordPress debugging mode’ section and change the global settings for your define WP_DEBUG to true. Setting the debugging mode to true is very important. Otherwise, your entire website would not print each time something goes wrong or you write a bad PHP code.

  3. Open the wp-content folder> plugins and create the plugin for your folder inside the plugins folder.

  4. Start building your plugin inside the newly created folder in your wp-content/plugins folder. You are to create every folder and file for your new plugin required in this folder.

1.3.2 Off WordPress core environment

This development process doesn’t require the developer to create the plugin files and folders inside the WordPress installation folder. The entire plugin is built in a different environment and moved to WordPress for use or testing. This is only ideal if you already have all the PHP, CSS, HTML and JavaScript files created and tested.

2.1 WordPress Plugin API: Hooks, Actions, and Filters

WordPress undergoes a lot of steps when loading a website and these steps exist as hooks. If you wish to make changes to your WordPress core behavior, you simply create a plugin that can hook unto the specific step you want to interfere. Hence, hooks represent the different stages or areas in a WordPress website which allows you to add a function in other to bring new changes. These functions are called hooked functions.

Hooks are WordPress features that allow you to manipulate a procedure or a stage in WordPress without editing the WordPress core. It can also be referred to as a generic term describing a place you can add your code (hooked function) to change a default procedure in WordPress. The syntax is as follows:

            add_action( 'hook', 'hooked function' ); 
Enter fullscreen mode Exit fullscreen mode

A hooked function is simply the code you want to place on the hook. They can be actions or filters.

Examples of a WordPress hook include wp_loaded, wp_footer, wp_admin_css, etc. See the WordPress developer reference page for a complete list of all the WordPress hooks.

Action hooks are hooked functions that implement the code and move on to the next step. Filter hooks return values, in other words, filters are hooked functions that would go back to the previous step in WordPress core to perform other functions during their execution.

2.2 Creating a coming soon page WordPress plugin

Following the above-mentioned procedure on how to create a WordPress plugin, we’ll be creating a simple coming soon/maintenance page plugin. This should serve as a guide as you create your first plugin. Remember, the hook determines where you wish to interfere in your WordPress core.

2.2.1 Features of the plugin

The plugin will trigger a coming soon or maintenance page on activation. And the page will be visible to every user even when they are logged in, except an administrator. In other words, websites with registered users can use the plugin for maintenance mode.

We will build the coming soon/maintenance page using HTML, CSS, and JavaScript.

2.2.2 Creating the plugin folders

The plugin will comprise of 6 folders:
•iu-coming-soon-page folder: the main folder containing all folders and files
  o assets folder, which will contain:
    images folder for all images
    css folder that will contain the css file, and
    js folder that will contain the JavaScript file
  o interface folder that will contain our HTML layout

2.2.3 Creating the main PHP file

Create a php file with the same name as the folder name. WordPress checks every plugin folder to find the php file with the exact name with the parent folder. That means our main file will be iu-coming-soon-page.php and placed directly inside the main directory, alongside our security file (index.php). We will include the plugin information as a block comment immediately after the opening php tag before writing the main PHP file code as shown below.

  Plugin Name: IU Coming Soon Page
  Plugin URI: enter plugin URL
  Description: Displays a coming soon page with a countdown to all users except the administrator
  Author: Ikechi Ude
  Version: 1.0
  Author URI: enter author's URL
  License: GPL2

  Copyright (c) 2020, Ikechi Ude 

 // this is our security check line
if (!defined('ABSPATH')) {

//our hook and hooked function
add_action( 'wp_loaded', 'IU_coming_soon_page');

//hooked function
function IU_coming_soon_page() {
        global $pagenow;
        if ( $pagenow !== 'wp-login.php' && ! current_user_can( 'manage_options' ) && ! is_admin() ) {
            header( $_SERVER["SERVER_PROTOCOL"] . ' 503 Service Temporarily Unavailable', true, 503 );
            header( 'Content-Type: text/html; charset=utf-8' );
            if ( file_exists( plugin_dir_path( __FILE__ ) . 'interface/comingsoon.php' ) ) {
                require_once( plugin_dir_path( __FILE__ ) . 'interface/comingsoon.php' );

Enter fullscreen mode Exit fullscreen mode

Above is our entire content for the main PHP file. The commented plugin information is all that is required for WordPress to recognize our PHP file as a plugin, provided the main file is placed inside the plugin’s main folder.

In our hooked function, we first sought for a condition that must be met before the function can fire our comingsoon.php file using the following conditional state:

function IU_coming_soon_page() {
    global $pagenow;  
            if ( $pagenow !== 'wp-login.php' && ! current_user_can( 'manage_options' ) && ! is_admin() ) {}              
Enter fullscreen mode Exit fullscreen mode

2.2.4 Creating the coming soon template

Our comingsoon.php file is the layout that will be seen by every other user. Hence, we have the freedom to play around with the position of our text, if we want to include links to our other platform like Facebook, and the message to everyone poised to see the coming soon page. While we write the HTML inside the php tags, it’s important to that we separate the CSS from the content to improve the readability of our code.

Below is the comingsoon.php file content.

 * Coming soon page template to be seen by all users except the administrator.
 * @package   coming-soon-page
 * @copyright Copyright (c) 2020, Ikechi Ude
 * @license   GPL2+
<!DOCTYPE html>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href="" rel="stylesheet">
    <link rel="stylesheet" href="<?php echo plugins_url( 'assets/css/comingsoon.css', dirname( __FILE__ ) ); ?>">
    <script type="text/javascript" src="<?php echo plugins_url( 'assets/js/js.js', dirname( __FILE__ ) ); ?>"></script>
    <title>Coming Soon | <?php bloginfo('name') ?></title>

        <div class="hero">
            <p><?php bloginfo('name')?> is currently under construction / maintenance, please check back</p>
        <h1>COMING SOON</h1>

            <p id="launch"></p>
Enter fullscreen mode Exit fullscreen mode

It’s your choice if you want to write an epistle to the audience explaining why your website is being maintained or still being delayed. I personally like it simple and short.

2.2.5 Creating the CSS and JavaScript

I named the css file comingsoons.css and the JavaScript comingsoon.js, both placed inside their respective folders in the assets folder.

Here’s the comingsoon.css file

    margin: 0;
    padding: 0;
    background-image: linear-gradient(rgba(0,0,0,0.5),rgba(0,0,0,0.5)),url("../images/image.jpg");
    height: 100vh;
    background-position: center;
    background-size: cover;

    top: 50%;
    left: 50%;
    position: absolute;
    transform: translate(-50%, -50%);
    color: #fff;
    text-align: center;
    font-family: 'Baloo Paaji 2', cursive;
    font-size: 60px;
    letter-spacing: 15px;

    width: 50%;
    margin: 30px auto;
    border: 1.5px solid #fff;
    font-size: 20px;
    margin-bottom: 30px;

    font-size: 40px;
    word-spacing: 20px;


Enter fullscreen mode Exit fullscreen mode

2.2.6 Including the JavaScript file to our plugin

Our JavaScript file is only necessary if we are interested in the countdown. However, you need to access the file each time you want to use this plugin to set a new launch date if the comingsoon.js file is in your plugin. Otherwise, you would display the wrong countdown time to your audience or a text depending on when last you had adjusted the date. I have December 25, 2020 in my JavaScript file. And "PLEASE CHECK BACK SHORTLY" as a replacement for the countdown time once it expires.

Here is the entire content for the comingsoon.js file.

var countDownDate = new Date("December 25, 2020 00:00:00").getTime();

    var x = setInterval(function() {

        var now = new Date().getTime();

        var distance = countDownDate - now;

var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);

document.getElementById("launch").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";

    if (distance < 0) {
        document.getElementById("launch").innerHTML = "PLEASE CHECK BACK SHORTLY";
    }, 1000);

Enter fullscreen mode Exit fullscreen mode

With every file saved in their respective folders, your plugin is ready to go live. If you are creating inside the WordPress installation folder, it’s time to see how your first plugin works by simply activating it. Otherwise, you want to zip the plugin and upload the zipped file onto your WordPress website, following the normal plugin installation procedure. Click on the activate button and see how it works. Remember to visit your website on a browser you’re not logged in as admin. I used the guest feature on Chrome in my test below.


2.3 Conclusion

Congratulations! You have completed a guide on how to create a WordPress plugin. You could continue from here to improve the plugin by adding its menu on your WordPress dashboard. The menu page may include an activation/deactivation toggle, a backend option to adjust the date in your JavaScript file, the coming soon message, and the background image which are currently hard coded.

You may invest some time to read up the WordPress Codex for more on WordPress core functions and inspiration on new projects. I hope this helps someone. I could update this article to explain the lines in more detail later on. Don't hesitate to share your view and if there's anything confusing.

The entire file can be downloaded from my GitHub repo using the link below

Top comments (2)

rafaacioly profile image
Rafael Acioly

Nice :)

have you ever tried ?

udeikechi profile image
udeikechi Author

That's a nice tool, sir :). But it's easier to move from point A to point B. Too many tasks could break the vibe :). Thanks for the addition.

🌚 Life is too short to browse without dark mode