Loading...

How to create a WordPress Plugin

2021-08-26 13:57:01
wordpress-plugin-development.png

You all know WordPress, the most widely used content management CMS in the world and you surely know that the tool works with a system of plugins or you would not be on this article.

I will explain to you how to create your first WordPress module as well as some essentials of plugin development for the CMS. This article requires some development knowledge and it is recommended that you know a minimum of the WordPress ecosystem to be comfortable with what will follow.

Publishing on the official WordPress plugin library is not mandatory, you can easily create a plugin that will be used only for your own needs. It will be a private plugin and it will have to be installed directly via FTP because it will not be available on the WordPress library.

What is a WordPress plugin?

Before getting into the technical part of creating a WordPress plugin, it is important to remember what a plugin is and when it may be appropriate to create one.

A plugin is a set of files to extend the options and functionality of the CMS. Indeed, it will make it possible to create new features that do not exist natively in the CMS or to modify some of them.

Yes of course, but the creation of a plugin allows you to create reusable, maintainable features that will not disappear with the change of the theme.

We can take for example WooCommerce, which is not a CMS but a WordPress extension allowing you to add an e-commerce part to your website.

As of this writing, there are 56,645 plugins listed on the official WordPress library (wordpress.org) but they do not constitute all of the existing plugins, some being found on other platforms. The field of possibilities is very wide, so it's impossible to say everything you could do with it, I leave your imagination free and browse the official WordPress plugins library.

It is therefore important to understand that WordPress plugins are real gems when you are the owner of a WordPress site. They will allow you to broaden the range of functionality of your website without having to get your hands dirty (normally).

If you are a WordPress developer, it's quite another thing because you yourself will create plugins for the community, your customers, or yourself in order to meet a need or a problem.

So I will explain how to create your first WordPress plugin in the rest of this article.

Prerequisites to create a WordPress plugin:

Some requirements before you start.

In order to be sure that you understand the rest of the explanations, it is necessary to know to program and in particular PHP, which is the language used by the WordPress CMS. For some advanced features such as the gallery, you will also need some knowledge of JavaScript. For the customization of your module, HTML / CSS is also very practical, especially if your extension is accessible by the user. In this case, it is better to know the integration and the responsiveness.

Knowledge of CMS is of course highly recommended, but you can learn as you go if you know the basics and want to discover plugin creation.

You must also have a local development environment such as MAMP, XAMP, LAMP, or directly apache on your system. If you are a developer, you should already have this. I also skip installing WordPress, if you haven't done anything yet, install the latest version of WordPress.

It is recommended to work on an up-to-date WordPress to take advantage of all the latest features and to ensure compatibility with the latest version of the CMS.

Finally, provide the code editor of your choice, the one that will allow you to work peacefully.

Personally, I use PHPStorm.

Creating the skeleton of your first WordPress plugin:

Are you ready to start your first plugin?

So here we go, here are the basics of creating a WordPress plugin.

To get started, it's very simple, your extension only needs one file to be recognized by the CMS.

Indeed, you just need to create a .php file in the / wp-content / plugins / folder. However, I recommend that you always create one file per module in order to have more clarity and to allow you better future maintainability.

To add a folder/file in the directory, I assume that you have your project locally on a test environment (MAMP, Xamp, Lamp…).

You can also access your live site from the FTP provided by your host, but I STRONGLY advise against it!

So we are going to create a module that will be called my-awesome-plugin, so create a my-awesome-module folder in / wp-content / plugins / then add a .php file of the same name to it.

You should have the nomenclature below:

wp-content /

- plugins /

—— my-awesome-plugin /

——— my-awesome-plugin.php

For your plugin to be recognized by your WordPress site, it must have a comment structure in the header of your file in this form

<?PHP

/**

 * Plugin Name: YOUR PLUGIN NAME

 */

?>

This is the minimum required for your module to appear in the list of other modules on the site.

You will surely have understood it, YOUR PLUGIN NAME must be replaced by the name of your plugin.

This name will appear in the list of extensions in the back office of the site.

However, there is more information available in this header to enrich your module with useful information.

For example, here is the header of one of my latest modules, as an example:

<?PHP

/**

 * Plugin Name: Lyskills

 * Plugin URI: https://www.lyskills.com

 * Description: Create & manage link’s hub for your social profile directly in your websites 

 * Version: 1.0.7 

 * Author Name: Lyskills(Lyskills.info@gmail.com) 

 * Author: Lyskills (Undefined) 

 * Domain Path: /languages 

 * Text Domain: lyskills

 * Author URI :https://www.lyskills.com #about

 */

You can find the full list in the official WordPress documentation under Header Requirements. This will allow you to add several information such as a description, the author of the plugin, the version number, or even technical information for the CMS.

From there, your plugin is available for activation from the site administration.

If you go to your back office on the “Extensions” page, you should see an additional line like this:

Congratulations, your first plugin is now created and you can activate it.

So far he's not doing anything in particular, but he has the merit of existing.

 

Use and explanation of hooks in WordPress

Now let's go further.

Now that your plugin exists and is activated on your site, we will see what a hook is and why it is essential in creating a WordPress extension.

You may already be familiar with hooks if you regularly edit themes or originate a custom WordPress theme.

Each CMS / Framework has its own way of functioning, but similarities appear when the user has to interact with the functionalities developed by the publisher.

The terms used vary from one CMS to another (or from one framework to another) but the operation is the same, you will position yourself in strategic places of the execution of the code thanks to events. Here (on WordPress) we use hooks.

If you are used to working in Magento for example, you are probably familiar with the Observers. If you know JavaScript, you necessarily know events, the operation is almost identical.

The hooks will therefore allow you to "listen" to the portions of code executed and to graft you at interesting times for your modifications. Provided that the editor is set up an action or a filter at the desired location.

Indeed, there are 2 types of hook, actions, and filters.

The action type, as its name suggests, will allow us to perform an action at a specific time. As for the filter, it will allow us to interact with data in order to modify or delete it.

Let's take an example to make it more meaningful.

We want our module to remove the “Articles” menu in the back office of the site because we don't use it.

To do this, we will use the action type hook with the identifier admin_menu, documentation available here: https://developer.wordpress.org/reference/hooks/admin_menu/

Thanks to the add_action function, you will be able to graft yourself to native code execution and add additional code, allowing you to remove the menu.

Here is the code needed to make this change.

<?php

function undefined_remove_menu_pages() {

        // allow you to delete the items menu

               remove_menu_page( 'edit.php' );

}

add_action( 'admin_menu', 'undefined_remove_menu_pages' );                            

The add_action function (as well as add_filter) has 4 parameters, 2 of which are optional.

$ tag (string) (Required)

The name of the action you want to target, here will be admin_menu

$ function_to_add (callable) (Required)

The name of the callback function you want to call, here will be undefined_remove_menu_pages.

$ priority (int) (Optional)

The level of execution priority of your code, in the event, that there will be several plugins using this hook for example. The higher it is, the more it will be executed last.

By default, the value is 10

$ accepted_args (int) (Optional)

The number of arguments accepted.

The specific action can provide you with various arguments containing information useful for the change you want to make.

By default, the number of arguments is 2, but you might need the 3rd or 4th argument to make your condition.

This change was made possible because the WordPress editor implemented a "listener" in the initial code. You can look in the WordPress core, you will find a do_action (‘admin_menu’, ”); in wp-admin / includes / menu.php

The same is true for filters, except that you must return a value at the end of your function and you will use the add_filter function instead of add_action.

Here is an example :                        

<?php

function undefined_edit_page_title($title) {

    return $title . ' | Lyskills' ;

}

add_filter('wp_title', 'undefined_edit_page_title');                                                         

Using this code, I changed all of my page titles on my WordPress blog to display, the page title before modification plus ‘| Lyskills ".

You will understand, hooks will be essential to modify the behavior of native WordPress features. Because obviously it is FORBIDDEN to modify the WordPress core directly. It is even an offense punishable by death! (It's a joke, of course, whatever ...).

Creation of an administration page in the WordPress back office using your module

Now that you know the hooks, we can create our first page in your site administration.

As I am a demanding developer and I consider that object-oriented programming has its place in WordPress (that it should even be the norm knowing that WordPress is not only written in procedural PHP), the examples that follow will be done as an object, but don't run away right away, you'll see everything I do is relatively easy to understand even for a novice.

Let's go back to our module created earlier and add the features we talked about.

 

To start, create a PHP class in your file (after the comments) like this:

class MyAwesomeClass

{

    public function __construct()

    {

        // Your code here

    }

}

 

new MyAwesomeClass()

The __construct method will be called upon instantiating your object.

So this is where we will put the add_action and add_filter.

We want to add a page to our administration as well as an associated menu in the left side menu of the back office.

For this, we will create the page in the back office using the admin_menu action. Add the following line in the __construct method:

add_action( 'admin_menu', [ $this, 'admin_awesome_plugin_menu'] );

As you can see, I am calling an array instead of the function name as the second parameter. I do so to be able to call a method of my current class.

The first parameter corresponds to my object, here it's $ this which returns my current object (my class). In the second parameter, the name of the method.

Then create the method of the same name. You will add the following code inside. The add_menu_page function will allow (as its name suggests) to create a page with an associated menu.

public function admin_awesome_plugin_menu()

{

        add_menu_page(

                                              __('My Awesome Plugin', 'my-awesome-plugin'), // Page title

                                              __('My Awesome Plugin', 'my-awesome-plugin'), // Menu title

                                                                 'manage_options',  // Capability

                                                                 'my-awesome-plugin', // Slug

                                                                  [ &$this, 'load_awesome_plugin_page'], // Callback page function

                                                                  );

}

Nothing complicated, I use the span class = "label"> add_menu_page function provided by WordPress and I choose the parameters that go well.

As you can see, I am calling another load_awesome_plugin_page method which will allow me to display content in my page. So create this method like this:

public function load_awesome_plugin_page()

{

        echo '<h1>' . __( 'My Awesome Plugin', 'my-awesome-plugin' ) . '</h1>';

        echo '<p>' . __( 'Welcome to My Awesome Plugin', 'my-awesome-plugin' ) . '</p>';

}

And there you have it, if you reload your back office, you will see on the left a menu with the name of 'My Awesome Plugin' which you can click to land on your new page.

It's simple, you just have to call on your talents as a developer to enrich your page with everything you need (forms, external calls, etc.).

Small tips in the development of your WordPress modules

Now that you've created your first WordPress plugin, it's time to give you some recommendations for making plugins that are clean, maintainable, and fun to use.

Code reading:

As with any development, you must make sure to write clean code, correctly indented, commented, and if possible documented to make it easier to read. This will be beneficial for the person who will read your code but also for you. If you go back to your code 6 months later and don't understand anything, it's not normal.

For our example, it is, therefore, more judicious to set up variables to avoid duplicates. So I create variables for the elements that would be repeated in the code of my plugin.

Find the entire module on the GitHub repo to see the changes.

Maintainability:

This goes hand in hand with reading your code, you must make your plugin easy to maintain and therefore plan for any future changes. So I advise you to put as many variables and constants as possible to avoid having to modify 20 files when you need to make a modification.

Also, split your code into different files so that each file is of use. It might seem obvious to some, but I still see too many modules with everything in one file and it's unreadable. To display content, for example, prefer separate templates rather than a galore echo in your .php file

For our example, it is, therefore, more judicious to load a template to display the content of our page.

Find the entire module on the GitHub repo to see the changes.

I also recommend that you put your plugin on a git repo in order to maintain it more easily and keep a history of changes. It will also allow you to better manage your updates.

Scalability:

When developing your module, think about the users who will be using your solution and the developers who would like to make changes without touching your code. To overcome this, it is strongly recommended to set up hooks as WordPress does at its core. It's very simple and it allows you to modify parameters or behaviors directly from another module or from the theme.

Let's imagine that your module launches a recurring task, you could for example put a hook of type filter on the duration between each execution.

For that, I invite you to go to the documentation of the function do_action and apply_filters.

Retroactivity:

Much like WordPress does, it is recommended that you keep your module working with older versions in case you make any changes to your module. So think about retroactivity.

Security:

We can never say it enough, but the security of your modules is essential! The user who will install your module on their website trusts your professionalism to do everything to avoid security breaches, especially if you interact with the database. for example, calls to MySQL should not be made any way or else it will attract malicious people.

Translate your WordPress module into different languages

Last important step in the creation of a module, the translation.

Indeed, it is customary for your developments to be carried out in English.

However, it is interesting and greatly appreciated that your module is also available in several languages. For this, WordPress benefits from an internationalization system that is very easy to set up.

You just have to create a / languages folder at the root of your project and create a .po file with the name of your module followed by - [LANGUAGE_CODE] which will give my-awesome-plugin-fr_FR.po for our module in the case of a French translation.

Add this to the file:

msgid ""

msgstr ""

"Project-Id-Version: My Awesome Plugin\n"

"POT-Creation-Date: 2020-05-03 15:37+1000\n"

"PO-Revision-Date: 2020-06-07 12:06+0200\n"

"Last-Translator: John Doe <john@doe.fr>\n"

"Language-Team: Awesome Team <john@doe.fr>\n"

"Language: fr\n"

"MIME-Version: 1.0\n"

"Content-Type: text/plain; charset=UTF-8\n"

"Content-Transfer-Encoding: 8bit\n"

"X-Generator: Poedit 2.2\n"

"X-Poedit-Basepath: ..\n"

"X-Poedit-WPHeader: my-awesome-plugin.php\n"

"Plural-Forms: nplurals=6; plural=(n==0 ? 0 : n==1 ? 1 : n==2 ? 2 : n%100>=3 && n%100<=10 ? 3 : n%100>=11 && n%100<=99 ? 4 : 5);\n"

"X-Poedit-SourceCharset: UTF-8\n"

"X-Poedit-KeywordsList: __;_e;_n:1,2;_x:1,2c;_ex:1,2c;_nx:4c,1,2;esc_attr__;esc_attr_e;esc_attr_x:1,2c;esc_html__;esc_html_e;esc_html_x:1,2c;_n_noop:1,2;_nx_noop:3c,1,2;__ngettext_noop:1,2\n"

"X-Poedit-SearchPath-0: .\n"

"X-Poedit-SearchPathExcluded-0: *.js\n"

 

msgid "My Awesome Plugin"

msgstr "Ma magnifique extension"

It might sound barbaric but these are configuration headers.

By browsing them, you will see that they contain information relating to our module as well as the language that we wish to translate.

 

However, this file will not be read by WordPress, the CMS reads .mo files, which are files compiled from .po files.

To compile your file, you can use Poedit software. Once downloaded, open your previously created file then go to File> Compile MO. It will create a .mo file in the languages folder containing your .po translation file.

Once your .mo file is ready, you need to tell your module that translation files exist. To do this, add the following code to your plugin.

This code in the __construct then the method in the class:

// in construcor method  __construct

add_action( 'plugins_loaded', [$this, 'load_plugin_text_domain'] );

 

// in classe

public function load_plugin_text_domain()

{

                    load_plugin_textdomain( $this->pluginIdentifier, FALSE, dirname( plugin_basename( __FILE__ ) ) . '/languages/' );

}

Once it's done, you should see your translation in the site's back office. If not, deactivate and then reactivate your module.

Conclusion:

You created your first WordPress module, so was it complicated?

It's up to you to leave room for your imagination to create many other modules, which will surely be more useful than this one 😀

Please feel free to browse the official WordPress documentation for more information on creating a WordPress plugin.

If you have any questions regarding the creation of a module, do not hesitate to contact us on Linkedin, Instagram, or by email.

whatsapp