Codementor Events

Creating a Wordpress plugin in 5 simple steps

Published Nov 19, 2019

Plugins are a way to add to or extend WordPress' built-in functionalities. There are thousands of useful plugins available from the online WordPress community, and they all perform different kinds of functions. You can install plugins that catch spam, back up your website, and give you basic SEO features. You can also get plugins that manage your podcasts, track your stats, translate your content into other languages, and much more.

Sometimes, however, you'll find yourself in a situation where the plugin you need just doesn't exist. Luckily, it's quite easy to write a plugin for WordPress that you can use on your own website and share with the larger community if you want to. All you need is some basic Hypertext Preprocessor (PHP) knowledge, and you can write any plugin you want.

This article is taken from the book WordPress 5 Complete - Seventh Edition by Karol Król. This book will help you build a great looking and function website in WordPress. You will learn how to create a blog site, use plugins and themes to customize the design of the site, and add some unique elements to set it apart. To follow along with the examples implemented in this article, you can download the code from the book’s GitHub repository.

In this article, we'll create a plugin via a simple step-by-step process. We'll first see what the essential requirements are, then try out and test the plugin, and then briefly discuss the PHP code involved.

Plugin code requirements

At the very least, your plugin must satisfy the following:

• It must be placed in the wp-content/plugins directory (inside the root directory of WordPress)
• It must have a PHP file with a unique name (that is, a name not used by any other plugin in the main wp-content/plugins directory)
• It must have a specially structured comment at the top of the file

Then, of course, you must have some functions or processing code; but WordPress will recognize any file that meets these requirements as a plugin.

If your plugin is a simple one, then you can just place a unique PHP file straight in your wp-content/plugins directory, so it can sit next to the default Hello Dolly plugin that WordPress comes with. However, a much better practice is to create a subdirectory (again, with a unique name) and place your PHP file there. It makes the wp-content/plugins directory seem much more organized. Plus, you never know when your plugin is going to need some additional files (it's always easier to simply add new files to a previously existing plugin directory, than to restructure the plugin from scratch).

A basic plugin – adding link icons

As a demonstration, we will create a simple plugin that adds icons to document links within WordPress. For example, if you create a new post and add a link to an MP3 file in it, it'll look something like the following screenshot:
a1.JPG

Once this plugin is complete, the link will look like the following screenshot:
a1.JPG

To accomplish this, we have to do the following:

  1. Provide images of the icons that will be used
  2. Have a PHP function that identifies the links to documents and adds a special CSS class to them
  3. Have a style sheet that creates the CSS classes for displaying the icons
  4. Tell WordPress that whenever it prints the content of a post (that is, using the the_content() function), it has to run the PHP function first
  5. Tell WordPress to include the new styles in the <head> tag

Naming and organizing the plugin files

Every plugin should have a unique name, so that it does not come into conflict with any other plugin in the WordPress universe. Apart from the main plugin file itself, your plugin can contain any number of other files and subdirectories. If the situation calls for it, you can even use media files, such as audio and video, to go along with your plugin. Of course, additional CSS or JS files (or even full libraries) are allowed as well.

In this case, as my plugin will be composed of multiple files (a PHP file, a style sheet, and some image files), I'm going to create a directory to house my plugin. I'll name the plugin Add Document Type Styles New, and place it in a directory called add_doctype_styles_new. The PHP file, doctype_styles_new.php, will live in this directory. I've also collected a number of document type icons (provided by Freepik via Flaticon).

The directory I created for my plugin now looks like the following:
a2.JPG

Now that I've got the images in my directory, I've taken care of the first requirement in the list of requirements my plugin has to meet.

As mentioned earlier, your plugin has to start with a special comment that tells WordPress how to describe the plugin to users on the plugins page. Now that I've got my directory and a blank PHP file created, I'll insert the special comment. It has to be structured like the following:

<?php 
/* 
Plugin Name: Add Document Type Styles New 
Plugin URI: http://nio.tips/
Description: Detects URLs in your posts and pages and displays nice document type icons next to them. Includes support for PDF, DOC, MP3, and ZIP. 
Version: 1.1 
Author: Karol K 
Author URI: http://karol.cc/ 
Text Domain: add_doctype_styles_new 
License: GNU General Public License v2 or later 
*/

That's all about the introductory code. Now, we can add the meat!

Writing the plugin's core functions

The core of any plugin is the unique PHP code that you bring to the table. This is the part of the plugin that makes it what it is. Since this plugin is so simple, it only has a few lines of code in the middle.

The second requirement the plugin has to meet is to have a PHP function that identifies links to documents and adds a special class to them. The following function does just that. Note that in keeping with my efforts to ensure that my code is unique, I've prefixed both of my functions with doctype_styles_new:

function doctype_styles_new_regex($text) { 
  $text = preg_replace('/href=([\'|"][[:alnum:]|
     [:punct:]]*)\.(pdf|doc|mp3|zip)([\'|"])/', 'href=\\1.\\2\\3 
     class="link \\2"', $text); 
  return $text; 
}

When the function is given some text,itwillperformasearchforanyHTMLanchortaglinkingtoaPDF,DOC,MP3,orZIPfile,andreplaceitwithaclasstothatanchor.Then,thefunctionreturnsthealteredtext*, it will perform a search for any HTML anchor tag linking to a PDF, DOC, MP3, or ZIP file, and replace it with a class to that anchor. Then, the function returns the altered *text.
The third requirement the plugin has to meet is to have a style sheet that creates classes for displaying the icons. The following function fetches our style sheet:

function doctype_styles_new_styles() { 
  wp_register_style('doctypes_styles', plugins_url
     ('doctype_styles_new.css', __FILE__)); 
  wp_enqueue_style('doctypes_styles'); 
}

Here's the CSS file that the preceding function fetches (inside doctype_styles_new.css):

.link { 
  background-repeat: no-repeat; 
  background-position: left center;  
  padding: 0 0 0 18px; 
} 
.pdf { background-image: url(icon-pdf.png); } 
.doc { background-image: url(icon-doc.png); } 
.mp3 { background-image: url(icon-mp3.png); } 
.zip { background-image: url(icon-zip.png); }

Adding hooks to the plugin

We get our code to actually run when it is supposed to by making use of WordPress hooks. The way in which plugin hooks work is as follows: at various times while WordPress is running, they check to see whether any plugins have registered functions to run at that time. If there are, the functions are executed. These functions modify the default behavior of WordPress.

There are two kinds of hooks, as follows:

Actions: Actions are the hooks that the WordPress core launches at specific points during execution, or when specific events occur. Your plugin can specify that one or more of its PHP functions are executed at these points, using the Action API.
Filters: Filters are the hooks that WordPress launches to modify the text of various types before adding it to the database or sending it to the browser screen. Your plugin can specify that one or more of its PHP functions is executed to modify specific types of text at these times, using the Filter API.

This means that you can tell WordPress to run your plugin's functions at the same time, when it runs any of its built-in functions. In our case, we want our plugin's first function, doctype_styles_new_regex(), to run as a filter along with WordPress' the_content() function (this is the fourth requirement a plugin has to meet).
Now, add the following code to the bottom of the plugin:

add_filter('the_content', 'doctype_styles_new_regex');

This uses the add_filter hook that tells WordPress to register a function named doctype_styles_new_regex() when it is running the function called the_content(). By the way, if you have more than one function that you want to add as a filter to the content, you can add a third argument to the add_filter() function. This third argument will be a number representing the load priority, and WordPress will run your functions in ascending order.

All that's left in our list of requirements that a plugin has to meet is the fifth requirement—that is, to tell WordPress to include the new styles in the <head> tag. This is actually done the same way that it's done for themes, which is through the following hook using add_action() with the wp_enqueue_scripts handle:

add_action('wp_enqueue_scripts', 'doctype_styles_new_styles');

Here is the complete plugin PHP file:

<?php 
/* 
Plugin Name: Add Document Type Styles New 
Plugin URI: http://nio.tips/
Description: Detects URLs in your posts and pages 
and displays nice document type icons next to them. 
Includes support for PDF, DOC, MP3 and ZIP. 
Version: 1.1 
Author: Karol K 
Author URI: http://karol.cc/ 
Text Domain: add_doctype_styles_new 
License: GNU General Public License v2 or later
*/ 
 
// this function does the magic 
function doctype_styles_new_regex($text) { 
  $text = preg_replace('/href=([\'|"][[:alnum:]|
     [:punct:]]*)\.(pdf|doc|mp3|zip)([\'|"])/', 
     'href=\\1.\\2\\3 class="link \\2"', $text); 
  return $text; 
} 
 
// this functions adds the stylesheet to the head 
function doctype_styles_new_styles() { 
    wp_register_style('doctypes_styles',      
    plugins_url('doctype_styles_new.css', __FILE__)); 
    wp_enqueue_style('doctypes_styles'); 
} 
 
// HOOKS ============= 
 
add_filter('the_content', 'doctype_styles_new_regex', 9); 
add_action('wp_enqueue_scripts', 'doctype_styles_new_styles');

Make sure you save and close this PHP file. You can now do one of two things, as follows:

• Using your FTP client, upload add_doctype_styles_new/ to your wp-content/plugins/ directory
• Zip up your directory into add_doctype_styles_new.zip, and use the plugin uploader in wp-admin to add this plugin to your WordPress installation

Once the plugin is installed, it will show up on the plugins page, as shown in the following screenshot:
a3.JPG

Now, you can activate it and test it out.

Trying out the plugin

If you go to view the same post that we created at the beginning of this article, you'll see the plugin in action. Here's the same screenshot again:
a1.JPG

You can also try adding a new post with links to PDF, ZIP, or DOC files. Then, when you view the post, you'll see that even more icons have been added to it by our plugin.
In this article, we learned how to create a basic plugin. If you found this post useful, do check out the book, WordPress 5 Complete - Seventh Edition on Packt Publishing. This book is an in-depth WordPress guide, covering everything about the platform such as WordPress posts, pages, themes, plugins, and more.

Discover and read more posts from PACKT
get started
post commentsBe the first to share your opinion
Show more replies