Connect with us

HOWTO'S

How to Create a Custom WordPress Plugin From Scratch

Published

on

Main Article Image

A theme is required for every WordPress site to pull data from the database and display it in a design. You could theoretically run a site using only a theme. But, this site would be extremely limited without plugins.

WordPress plugins are an extension of WordPress core that adds additional functionality to your site. Plugins can be used to add everything to your WordPress site, from an animated slide or booking calendar to a fully-featured learning management system and online marketplace.

This guide will show you how to make your own WordPress plugin. I will show you best practices in plugin development, how to get your plugin to run, as well as how to organize your plugin’s files and code. You’ll also find some frequently asked questions and a walkthrough of how to create your first plugin.

WordPress plugins available for free and paid

There are many places where you can download or buy plugins to enhance your website. You can find thousands of plugins in the WordPress plugin directory that will help you build the website you want. If you are looking for advanced features, better support or a better user interface, premium plugins can be purchased from CodeCanyon.

Codecanyon%20shortcode%20plugins

Sometimes, however, you may need to create your own plugin. You might not need all the code from third-party plugins, so this can be more efficient. This allows you to create a plugin that suits your needs better, or modify an existing plugin to suit your site.

What are the Essentials to Create a Plugin?

You will need the following:

  • a code editor
  • A development WordPress installation is provided with a copy your live site to test.

Test your plugin only on your live website once you are certain it works.

If you don’t have a WordPress local installation, please follow our guide to copying and installing your site to a local install . If you are unable to install WordPress locally, you can use a backup of your site on your server. Learn how you can copy your site.

Advertisement

Types of WordPress plugins

Many plugins are capable of performing many tasks. They all add functionality to your website. There are many types of WordPress plugins.

  • Site Maintenance Plugins to help with security, backups, and performance
  • Marketing and Sales Plugins For things like SEO, Social Media, or eCommerce
  • Content Plugins including custom post types, widgets and shortcodes, forms, galleries and video feeds
  • API plugins which work with the WordPress API or pull in content from services such as Google Maps
  • Community plugins which add social networking features

You can do so much more! You can get an idea of the potential uses of plugins by looking at the WordPress plugin directory or the CodeCanyon marketplace.

WordPress%20plug in%20directory

What goes into a plugin?

Before you start building your plugin, it is worth understanding what goes into it. The exact look of your plugin’s code will depend on the type of plugin. Some plugins are very small with only one file, while others have multiple files with scripts, stylesheets and template files. There are many plugins that fall somewhere in between.

These are the elements that you will likely have in your plugin:

  • The main plugin file (this is crucial)
  • folders for different file types
  • Scripts
  • Stylesheets
  • Include files to organize the code

Let’s take a closer look at each one.

The Main Plugin File

It is vital to have the main plugin file. It will always be a PHP-file and will always include commented-out text telling WordPress about your plugin.

Here’s an example from Akismet:

<?php
 
/**
 
 * @package Akismet
 
 */
 
/*
 
Plugin Name: Akismet Anti-Spam
 
Plugin URI: https://akismet.com/
 
Description: Used by millions, Akismet is quite possibly the best way in the world to <strong>protect your blog from spam</strong>. It keeps your site protected even while you sleep. To get started: activate the Akismet plugin and then go to your Akismet Settings page to set up your API key.
 
Version: 4.1.7
 
Author: Automattic
 
Author URI: https://automattic.com/wordpress-plugins/
 
License: GPLv2 or later
 
Text Domain: akismet
 
*/

This information tells WordPress about your plugin, its location, who created it, and what it does. It also gives information about the version number and the text domain and path for internationalisation, as well as the license.

WordPress uses this information to populate your plugins screen. This is how Akismet appears on that screen.

Advertisement
Akismet%20in%20the%20plugins%20admin%20screen

As you can see, the information in the plugin file was used to populate the entry and provide links.

Additional information about the plugin can be found in the README.txt file. This file is used to populate plugin’s page in plugin directory.

Akismet%20in%20the%20plugins%20directory

The code that runs the plugin will be found in the main plugin file. Sometimes this will contain all of the PHP needed to run the plugin. However, larger plugins may require additional code to be included in the main plugin file. This allows you to organize your code and makes it easier to use. Later in this guide, I will show you how to use include file.

Folder Structure

Although there aren’t any hard and fast rules about how to organise your folders in your plugins, it is a good idea to follow the same pattern as other plugin developers. This will allow you to familiarize yourself with how other plugins work and will help you communicate your code to others.

Your plugin may contain the following folders:

  • CSS or style to stylesheets
  • scripts JavaScript
  • includes for include files
  • templates to be used in template files.
  • assets to media and other asset file
  • i18n internationalisation files

If your plugin is complex or large, you might need more folders. WooCommerce, for example, has folders to store sample data and packages. These folders contain subfolders that can be used to store admin files and blocks.

WooCommerce%20files

Stylesheets and scripts

Stylesheets are required if your plugin produces content that requires styling. This could be in the admin screens or the front-end. If your plugin uses scripts, stylesheets will be required.

Even if you have only one, it makes sense to keep them in their own folder. These scripts and stylesheets will need to be enqueued using a specific function in your main plugin. This is how I will show you when we build the plugin.

Include Files

Splitting your code into multiple files called include files can help you organize your plugin. These files can then be placed in their own folders and called from your main plugin file with an include, or need function.

This allows you to keep your bulk of code in a well-organized file structure, while your main plugin file is kept small and manageable.

Advertisement

You don’t have to use include files if your plugin is small. Simply add your code to your main plugin file. To maintain a logical structure, you may need to organize the file and reorder functions as you add them.

These are the most commonly used elements in a plugin. As we’ve seen with WooCommerce, there are many other elements. You can also have many smaller plugins. These elements will be more frequently used as you create more plugins.

How to Run Your Plugin Code

Activating your plugin is the first step to enabling it to work. You have a few options to activate your code, or pull in code from WordPress.

  • Functions
  • Action and filter hooks
  • Classes

Let’s take a closer look at each one.

Functions

Functions are the foundation of WordPress code. These functions are the easiest way to start writing your own plugins, and they’re also the most straightforward to code. They’re also found in the themes’ files.

Each function will be given a name and then braces with the code within them.

Your plugin’s code won’t run unless it calls the function. This is the simplest, but least flexible way to do it. You can call the code directly in your theme or elsewhere in your plugin.

Advertisement

Here’s an example of a function:

tutsplus_myfunction {
 
// code goes here
 
}

To directly call that function in your theme, you’d simply type tutsplus_myfunction() in the place in your theme template files where you want it to run. You could also add it to your plugin, but you would need to activate it.

These limitations are:

  • You can’t activate a function that does more than adding content to a theme template file.
  • You will need to call the function again and again if you want it to be called in more than one place.
  • It can be difficult to keep track all the functions you have manually called.

It is a better idea to attach functions to a hook to be able to call them.

Filter and Action Hooks

Attaching your function to an hook allows you to run it whenever the hook fires. There are two types: filter hooks and action hooks.

Action hooks are not useful. WordPress does not respond to action hooks unless it has been connected to a function.

Filter hooks are code that will run , unless there’s a function hooked up to that hook. If there’s a function attached to the hook, it will run that function. You can either add default code to your plugin and override it with another plugin or write a function to override the default code attached to a filter hook within WordPress.

Advertisement

Three ways to fire hooks:

  • WordPress. There are hundreds of hooks in the WordPress core code that can fire at different times. Depending on the function you are hooking, which one you use will determine what you need. The developer handbook contains a list WordPress hooks.
  • Your theme. You can add additional content to key areas of your website’s design by using action and filter hooks. All themes include a wp_footer hook. These can be combined with conditional tags to allow you to run specific code on particular pages within your site.
  • Your plugin and other plugins. An action hook can be added to your plugin. Then, you might include functions in your include files to attach code to the hook. You might also write a filter hook that allows you to override certain functions. You can also hook your functions to an existing hook in a third-party plugin if you are creating a plugin. This is what I did with WooCommerce to customize the output of product pages.

While some of these are more advanced, your first plugin will hook your functions to an action/filter hook output by WordPress, most likely an Action Hook.

Classes

Classes allow you to code more complicated features such as customizer elements and widgets, using the existing WordPress APIs.

You’ll likely be adding a class to your plugin by extending an already-coded class. You can use the code provided by the class to modify it to your liking. You might use the customizer as an example. Here you could write a class that includes a color picker and make use of the color picker interface provided in the existing customizer class.

Classes are more complex than functions and you won’t be able to do it with your first plugin. For more information, please refer to our guide to classes for WordPress.

Even if you write classes, actions and filters will still be required to make them run.

Best Practices for Plugins

It is important to learn best practices before you begin coding your plugin. This will ensure that your code is high-quality right from the beginning.

Advertisement

These include:

  • WordPress coding guidelines will guide you in writing your code. You will need to submit your plugin for inclusion in the plugin directory.
  • Comment your code to make it easier for others to work with. This will help you to remember how it works when you return to it later.
  • Prefix your functions, hooks, or classes with prefixes to make them unique to your plugin. It is not a good idea to name a function the exact same as another function in WordPress core or another plugin.
  • Your folders should be organized logically. Keep your code separate so that others can understand it. Also, so that you can add to it as needed without making it a mess.

It might seem that best practice doesn’t matter if you’re the only one using the plugin. Your plugin may grow over time. You might allow others to use it or sell it. You might forget how it is organized in two years.

In 4 Easy Steps, Create Your First Plugin

At last! Now that you have an understanding of plugins, it is time to get started creating your first plugin. This tutorial will show you how to create a simple plugin that registers custom post types.

This is a common use of a plug-in, and one you can continue to build upon over time to add custom templates files for your post type or other functionality.

I will show you the basics of the plugin, and then give you an overview of how you can add to it.

1. Create the Plugin Folder and File

Even if your plugin starts small, even if it only has one file, it is a good idea to give it its own folder. Create a folder within your WordPress Content/plugins directory. Create a PHP file inside that folder for your plugin.

Both folders should be given a name that is logical and includes a prefix. I’m calling my folder tutsplus-register-post-types and my file tutsplus-register-post-types.php.

Advertisement

Open your plugin file, and then add the commented-out information to the top. Take my example below and modify it to reflect that this plugin is yours.

<?php
 
/*
 
Plugin Name: Tuts+ Register Post Types
 
Plugin URI: https://tutsplus.com/
 
Description: Plugin to accompany tutsplus guide to creating plugins, registers a post type.
 
Version: 1.0
 
Author: Rachel McCollin
 
Author URI: https://rachelmccollin.com/
 
License: GPLv2 or later
 
Text Domain: tutsplus
 
*/

Save your file, then go to the plugins screen on your development site. You’ll see the plug-in there.

New%20plugin%20in%20the%20plugins%20admin%20screen

It can be activated if you wish, but it won’t do anything because you haven’t added any code. Let’s get started.

2. Add Functions

Now, it’s time for the first function to be written in our plugin. Make your plugin by adding the braces that will contain the code. Here is mine:

function tutsplus_register_post_type() {
 
    // movies
 
    $labels = array( 
 
        'name' => __( 'Movies' , 'tutsplus' ),
 
        'singular_name' => __( 'Movie' , 'tutsplus' ),
 
        'add_new' => __( 'New Movie' , 'tutsplus' ),
 
        'add_new_item' => __( 'Add New Movie' , 'tutsplus' ),
 
        'edit_item' => __( 'Edit Movie' , 'tutsplus' ),
 
        'new_item' => __( 'New Movie' , 'tutsplus' ),
 
        'view_item' => __( 'View Movie' , 'tutsplus' ),
 
        'search_items' => __( 'Search Movies' , 'tutsplus' ),
 
        'not_found' =>  __( 'No Movies Found' , 'tutsplus' ),
 
        'not_found_in_trash' => __( 'No Movies found in Trash' , 'tutsplus' ),
 
    );
 
    $args = array(
 
        'labels' => $labels,
 
        'has_archive' => true,
 
        'public' => true,
 
        'hierarchical' => false,
 
        'supports' => array(
 
            'title', 
 
            'editor', 
 
            'excerpt', 
 
            'custom-fields', 
 
            'thumbnail',
 
            'page-attributes'
 
        ),
 
        'rewrite'   => array( 'slug' => 'movies' ),
 
        'show_in_rest' => true
 
    );
 
}

This includes all of the arguments and labels for your post type, and (crucially), the register_post_type() function that is provided by WordPress.

As I am creating a movie review website, I have used movies as my post type. You may want to try something else.

You’ll notice that nothing has changed if you save the file and then go back to your website. This is because your code has not been activated. We activate the function by hooking it up to the init hook, which is provided by WordPress. You can use the function provided by WordPress (e.g register_post_type), but there is a hook you should use. Details can be found in the WordPress handbook entry Registering custom post types.

Advertisement

Let’s now add the hook. Add the following line to your code.

add_action( 'init', 'tutsplus_register_post_type' );

To hook our code to an Action Hook, we use the Add_ACTION() function. It has two parameters: The name of the action hook as well as the name our function.

Save your files now and go back to your website. If you activated the plugin, you will see the custom post type in your admin menu.

New%20post%20type%20in%20admin%20menu

It’s great!

Let’s now add an additional function to register a custom taxonomy. Add this to the code that you have written so far:

function tutsplus_register_taxonomy() {    
      
    // books
    $labels = array(
        'name' => __( 'Genres' , 'tutsplus' ),
        'singular_name' => __( 'Genre', 'tutsplus' ),
        'search_items' => __( 'Search Genres' , 'tutsplus' ),
        'all_items' => __( 'All Genres' , 'tutsplus' ),
        'edit_item' => __( 'Edit Genre' , 'tutsplus' ),
        'update_item' => __( 'Update Genres' , 'tutsplus' ),
        'add_new_item' => __( 'Add New Genre' , 'tutsplus' ),
        'new_item_name' => __( 'New Genre Name' , 'tutsplus' ),
        'menu_name' => __( 'Genres' , 'tutsplus' ),
    );
      
    $args = array(
        'labels' => $labels,
        'hierarchical' => true,
        'sort' => true,
        'args' => array( 'orderby' => 'term_order' ),
        'rewrite' => array( 'slug' => 'genres' ),
        'show_admin_column' => true,
        'show_in_rest' => true
  
    );
      
    register_taxonomy( 'tutsplus_genre', array( 'tutsplus_movie' ), $args);
      
}
add_action( 'init', 'tutsplus_register_taxonomy' );

You might also want to modify the name of your custom taxinomy. Here, the taxonomy is applied to the post type that I just registered (the third parameter in the register_taxonomy operation). You can edit the bit if you gave your post type another name.

Save your file now and go to your admin screens. The new taxonomy will be visible if you hover over the post type in your admin menu.

Advertisement

Now you have a working plugin. Well done!

Let’s look at what you can do to make it better.

3. Enqueue Stylesheets and Scripts

You can add custom styling and scripts to your plugin files if you have the need. However, this is not the best practice. Instead, create stylesheets or scripts in separate files within your plugin folder, and then enqueue them using a WordPress function.

Let’s say you want to add styling to your custom post type. This could be added to your theme. However, you may want to add specific styling to the plugin in order to make the custom post type stand out from all other types of post types.

You will need to create a folder in your plugin folder named CSS or styles. You can name your stylesheet style.css or give it a specific name to make it easier to find. My movies.css.

The file must be enqueued in your plugin to allow WordPress to use it. This should be added to the main plugin file. Enqueuing and include are important to me. This allows me to see which files are being activated.

function tutsplus_movie_styles() {
    wp_enqueue_style( 'movies',  plugin_dir_url( __FILE__ ) . ‘/css/movies.css’ );                      
}
add_action( 'wp_enqueue_scripts', ‘tutsplus_movie_styles' );

You won’t notice any changes in your admin screens if you save your file. However, if you have added custom post types and your stylesheet includes styling, you will now see them in the front-end.

Advertisement

The hook for enqueuing stylesheets and scripts are the same. They both use wp_enqueue_scripts. There is no separate hook for styles.

The same way that Enqueuing scripts work is for query scripts. These are the steps to follow:

  • To your plugin folder, add a scripts and js directory.
  • There are script files that you can save.
  • You can now queue the script the same as the stylesheet, substituting the style() function by Enqueue_script()

4. Use Include Files

You can also create additional PHP files as part of your plugin development. These are known as include files. You might have multiple include files, so you could create several folders or one folder named includes.

You can use a few functions to include files. These functions are covered in our comprehensive guide to including requiring files.

We might, for example, create code in our custom plugin to change the output of the page’s content. This could be done by using the the_content filter hook. The code will then be modified each time that the product page displays the content.

You could instead of adding the code to the main plugin folder, create a separate movie-content.php file and then add the code there to control the output for movies.

You add the content-movie.php folder to your plugin in order to include this file.

Advertisement

This code is needed to include the file in your plugin.

include( plugin_dir_path( __FILE__ ) . ‘includes/movie-content.php' );

This doesn’t have to be hooked to any action or filter hook. Just use the include_once() function within your plugin file. This will call the code in the include file just like it was in the main plugin file.

How to extend or edit an existing plugin

Sometimes, you may find a plugin from a vendor or in the plugin directory that does all you need. You might also want to tweak or customise a plugin.

WordPress is open-source makes it possible. It is possible to take the code of another plugin and modify it to make it function as you wish.

Two ways to accomplish this are available:

  • Fork an existing plugin, i.e. Edit it to make it more reliable or work differently.
  • Create your plugin to extend the original plugin.

Editing an existing plugin is easy: You create your own copy on a site that you have created (never live!) You can make changes to the plugin as necessary. To avoid any problems, make sure to use version control.

Although it is more difficult to extend a plugin using your own plugin, it is more reliable.

Advertisement

Hooks and classes are a common feature of popular plugins. Hook into action and filter hooks, and extend classes to create your own code. This code uses an existing plugin’s base code but adds or changes it.

WooCommerce, for example, has many functions, hooks and classes. It even has its own API. These functions, hooks, and classes power every part of WooCommerce. You must identify the code that is driving the WooCommerce system, then create your plugin to attach to it or extend the classes.

This is how you can customize a plugin such as WooCommerce. I used it once to power a listing site without a checkout. Hooks were used to remove unwanted elements and create new ones.

You can hook into WooCommerce to extend it or add your own plugin. See our guides to adding product description to archive pages, and to adding product-based blogs to your store. These are just a few examples of what you can do, but they will give you an idea of where to begin.

Take It Further: Plugin Features

This guide will show you how plugins work and how to start building your own plugin.

Once you are proficient in plugin development, you will be able to create more complicated and fully-featured plugins that can perform more complex tasks for your site.

Advertisement

Let’s look at some examples.

Widget Plugins

Although widget plugins require you to work with classes, they are a great introduction to the topic. This guide will show you how to create a widget plugin.

CodeCanyon also offers many widget plug-ins, which can be used to save time and effort in coding. We’ve identified the top widget plugins for 2021 and the best Facebook widgets as well as the most useful Twitter widgets.

Code%20Canyon%20widget%20plugins

Shortcode plugins

A shortcode is an excellent place to begin creating plugins. They are simple and extremely useful. Learn how to create them in our coding guide for WordPress.

CodeCanyon also offers a number of shortcode plugins that you can use to enhance your website’s functionality.

Code%20Canyon%20shortcode%20plugins

Social Media Plugins

Social media plugins are extremely popular because they allow you to display your Instagram, Twitter, and Facebook feeds on your website, and allow your visitors to share your content through their social media accounts.

CodeCanyon offers many social-media plugins. Find out which social media plugins are the best and how to build an online community for WordPress.

Gallery and Media Plugins

A plugin can make your site look professional and optimise your media. Learn how to create your own gallery plugin. You can also browse the professional gallery or video plugins at CodeCanyon.

Advertisement
media%20plugins%20on%20Code%20Canyon

Form Plugins

Your visitors can contact you by adding forms to their site. This helps them build a connection. CodeCanyon offers many premium forms plugins to make it easier for visitors to get in touch with you. Learn how you can create a form using the popular QuForm plugin.

Summary

Plugins can transform your website from a blog to a robust, secure, and robust website. To improve your WordPress website, you can add plugins to your site or code your own.

The Best WordPress Themes and Plugins on Envato Market

Explore thousands of the best WordPress themes ever created on ThemeForest and leading WordPress plugins on CodeCanyon. Purchase these high-quality WordPress themes and plugins and improve your website experience for you and your visitors.

themeforest%20popular%20wordpress%20themes

First seen at Tutsplus.com

Keep an eye on what we are doing
Be the first to get latest updates and exclusive content straight to your email inbox.
We promise not to spam you. You can unsubscribe at any time.
Invalid email address