WordPress Plugin Development: The Basics Explored

Last Updated on September 23, 2022 by 8 Comments

WordPress Plugin Development: The Basics Explored
Blog / Tips & Tricks / WordPress Plugin Development: The Basics Explored

One cannot be praiseworthy enough of the way in which WordPress has been built to extend endlessly via its plugin ecosystem.

Yet plugins sometimes get a bad rap. Anyone who’s been using WordPress for more than five minutes will have found themselves, at one time or another, bemoaning a particular plugin due to any number of issues.

But let’s be clear: Plugins are not the problem. The problem is bad code and bad development practices – things that any developer worth his or her salt should have a handle on.

With the above in mind, in this article I want to focus on the basics of plugin development. This article is intended to be a great primer for newbies to WordPress plugin development, as well as a reminder of best practices for more experienced developers.

Let’s get started!

Should I Use a Plugin or an Alternative?

Given that code can be implemented either in a plugin or a theme, you might often find yourself wondering about the right course of action. Should your code go into a plugin, or are alternatives more appropriate?

Know the Purpose of Your Code

As a rule, if the new feature you intend to add represents a change to your theme’s design, it should be added to a child theme. On the other hand, if the intended feature introduces or changes functionality, it goes through a plugin.

That said, there isn’t always a clear line between function and design. In situations like these, a simpler approach would be to consider if you would like to keep the new feature available when you decide to switch design/theme of your website, which brings us to our next point.

Plugins are Theme Independent

Any code you add to a child theme will disappear the moment you switch themes. It sure would be troublesome to salvage all those tiny bits of code you added. In several cases, it can be difficult enough to just find those bits of code.

That’s where plugins beat changes made through child themes and/or the functions.php file. Your code stays with you and is available for deployment alongside a new theme. It is essential that the user be able to switch designs without fearing any loss in functionality. Don’t need the functionality? Simply deactivate the plugin.

You Can Easily Scale a Plugin

Plugins are great at compartmentalizing code. You get a sweet bit of code lined up that can be easily modified and scaled to suit your needs. That alone works so much better than plowing code into the functions.php file and living in fear of the “white screen of death” the moment you save your changes.

Plugins can be super simple – like Hello Dolly – or complex enough to bring sweeping changes throughout your website – like WooCommerce – so scalability really does become important.

There’s also a hidden benefit to deploying functionality through plugins: You can release your plugin to the larger WordPress community, and perhaps even commercialize it in the future.

Can You Have Too Many Plugins?

Plugins being “bad” for your WordPress website is a myth that pervades not so much because of inherent shortcomings of plugins, but more because these beliefs seem to have taken on the dimensions of an urban legend.

Let’s have a quick look at some myths associated with plugins:

  • Code in themes performs better than code in plugins.
  • Plugins slow down your website.
  • Plugins are resource hogs.

There can be truth to these claims, that shouldn’t discourage you. There is no difference between a chunk of code being executed by a theme or by a plugin, except for (in some cases) timing. Plugins generally will load their associated databases, stylesheets and scripts. So will code placed in the theme!

The problem usually is plugins loading non-required resources, or loading resources even if they are not needed. For example, you might have set your social sharing plugin (such as Monarch) to be visible only on permalink or single post pages. Yet some plugins may load their resources on the index page as well, while staying invisible. Or some users might have multiple plugins for sharing, thus loading similar resources multiple times for a page.

It’s a problem in the way users or developers handle plugins – it is not an issue with plugins per se.

In other words, plugins don’t take more resources or more time than code elsewhere; problems result from bad code and following poor practices during WordPress plugin development.

WordPress Plugin Development Best Practices

Best practices are the cornerstone to developing a good plugin. Just like making your code readable is advantageous in terms of future development, following best practices fine-tunes your plugin and takes away the headaches that a bad plugin might bring later.

Irrespective of the skills you use for the plugin, it is best practices that will define how well your plugin can really perform. Ideally, a WordPress plugin should work with the following best practices in mind:

Prefix Everything

Have a unique identifier to work with your plugin (similar to ‘wp’ used by WordPress). Every file, variable and function should get that unique identifier. In most cases, it can be the initials of your plugin name, or you can get a bit creative – as long as the prefix is relevant and unique.

Use a Clean Folder Structure

The root level of your plugin directory should not contain files other than plugin-name.php and (optionally) the uninstall file. Everything else goes into relevant directories. Javascript goes into a ‘js’ directory, images go into an ‘images’ directory, and so on.

Make Way for Expansion

If you intend to expand the plugin’s functionality, develop the plugin architecture in a way that leaves room for future changes. Simple plugins might not require this, but if you envision scope for future development, get your plugin architecture right up front.

Never Write a Plugin Without the Debug Mode On

The first thing you do when you set out to write a plugin is turn on the debug mode. WordPress raises errors when things go sideways for development, but there would be no way for you to know that if the debug mode wasn’t active to flag the errors.

As another advantage, the debug mode keeps you up-to-date with latest WordPress functions. With all the changes and updates flowing, it might not be possible to keep tab on new functions or functions being deprecated.

To enable the debug mode, head to the wp-config.php file (backup before you make changes!) in the WordPress root directory and find the following line:

define('WP_DEBUG', false);

That line needs to be replaced with:

 // Switch on debugging

define('WP_DEBUG', true);

// Direct WordPress to the <a class="wpil_keyword_link" href="https://www.elegantthemes.com/blog/tips-tricks/using-the-wordpress-debug-log"   title="debug log" data-wpil-keyword-link="linked">debug log</a> file /wp-content/debug.log file

define('WP_DEBUG_LOG', true);

// PHP 'display_errors' variable is not forced

define('WP_DEBUG_DISPLAY', false);

// Stops errors from being displayed onscreen

@ini_set('display_errors', 0);

It’s as simple as that!

Actions and Filters Explained

Plugins run by making use of WordPress hooks to modify and interact with code. There are two types of hooks:

1. Actions

To put it simply (and literally), Actions represent something that has happened. They can be used to add functionality or change the way WordPress operates. WordPress invokes Actions at certain points or with the occurrence of certain events.

Actions can be used for a variety of purposes, such as modifying your WordPress dashboard, or, like in the following example, adding custom text and URL to the toolbar:

 add_action( 'wp_before_admin_bar_render', 'wwtp_modifying_toolbar_example' );

function wwtp_modifying_toolbar_example() {

    global $wp_admin_bar;

    $wp_admin_bar->add_node( array(

        'id'    => 'site-developer',

        'title' => 'Reach out to the Website Developer',

        'href'  => 'https://www.elegantthemes.com/,

        'meta'  => array( 'target' => '_blank' )

    ) );

}

Notice the use of wwtp as the prefix, simply as a unique prefix to set the code towards good practice.

WordPress Plugin Development - Using action on toolbar

The WordPress Codex has a list of actions that can be used to make changes to your WordPress.

2. Filters

Filters are hooks that interact with data; they can manage and change data as it flows from the database to the browser, or the other way round. For example, consider a scenario where the browser has requested a post. As WordPress transfers the post to the browser, it will apply any filters that have been added.

You can use filters to clean up a web page’s permalink. In the example here, I’ll remove of from the permalink – a good way to get rid of the stop word.

 add_filter( 'sanitize_title', 'wwtp_remove_of_stopword' );

function wwtp_remove_of_stopword( $title ) {

    $title = str_replace( '-of-', '-', $title );

    $title = preg_replace( '/^of-/', '', $title );

    return $title;

} 

Again, the WordPress Codex is a great resource for keeping yourself informed about filters.

How to Create Your Own Plugin (The Basics)

Now that we have a handle on the concepts that go into WordPress plugin development, we can drive through the steps that go into creating a plugin.

The first thing you need to do is decide on the name of the plugin and the unique prefix you are going to use.

Navigate to the directory wp-content/plugins and create a folder named after your plugin. For our current purposes, let’s just call it mytestplugin.

The plugin’s directory can now host the PHP file required for the plugin; let’s name it wwtp_mytestplugin.php. Remember – following best practices – if there are any more files, they should go into specific directories. Ideally, only one file should stay at the root level.

Now we need to tell WordPress that our little file represents a plugin. We’ll add some parameters to the file so WordPress knows that it’s dealing with a plugin:

<?php

/**

* Plugin Name: My Test Plugin

* Plugin URI: http://add_your_uri_here.com/

* Description: Tell the world what your plugin wants to achieve.

* Version: 1.0 adding a version is always handy.

* Author: Your name

* Author URI: If your personal website is different than the plugin website, it goes here.

* License: A license name

*/

Voila! WordPress knows you have a plugin.

WordPress Plugin Development - Activated test plugin

Now that WordPress knows about our plugin, how about having it do something? Let’s leave a message on the post editor. Just add this code to follow the previous set, and the plugin can move into action:

 add_filter( 'the_editor_content', 'wwtp_adding_text_notes' );

function wwtp_adding_text_notes( $content ) {

    // Only add this text if the box is empty. We don't want to mess up drafts!

    if ( empty( $content ) ) {

        $template  = 'Hey let us start writing...' . "\n\n";

        $template .= '<ul><li>Add useful text</li><li>Make good use of images</li><li>And don\'t forget the alt text!</li></ul>' . "\n\n";

        return $template;

    } else

        return $content;

}

Here’s how our plugin looks in action:

WordPress Plugin Development - Test Plugin Result

Now that you have the basics of WordPress Plugin development clear, you might want to try your hands at something more advanced. Andy’s article on developing a WordPress plugin is an excellent place to start your journey towards the creation of more complex plugins.

Conclusion

Knowing the basics of WordPress plugin development can be beneficial every user of this CMS. Adding functionality can be much easier once you accept the power of plugins and part with misgivings against these very useful bits of code.

Just follow best practices to keep your plugin trim and in good health, and you can enjoy the resultant scalability and flexibility. You don’t always need to find a plugin for your needs; you can handle the simple tasks yourself.

Now you know the basics to adding custom functionality to your site and keeping it theme independent. Don’t worry about the number of plugins you can add – use as many as you like, but keep your focus on quality plugins.

Let us know your plugin stories and experiences with developing your own plugins in the comments below!

Image Credit: retrorocket / ShutterStock

Divi

Want To Build Better WordPress Websites? Start Here! 👇

Take the first step towards a better website.

Get Started
Divi
Premade Layouts

Check Out These Related Posts

Splice Video Editor: An Overview and Review

Splice Video Editor: An Overview and Review

Updated on March 10, 2023 in Tips & Tricks

Video is a valuable form of content for social media. Unfortunately, creating quality videos is usually a long process that involves moving mobile footage to a desktop app for editing. However, mobile editing is on the rise. Apps such as Splice Video Editor make it possible to efficiently create...

View Full Post
How to Use Font Awesome On Your WordPress Website

How to Use Font Awesome On Your WordPress Website

Updated on September 16, 2022 in Tips & Tricks

When given the choice between using a vector icon or a static image, it’s a good idea to go with the vector. They’re small and fast to load, and they can scale to any size without a loss of resolution. Font Awesome is a superb library of vector icons that you can use on your websites,...

View Full Post

8 Comments

  1. Great article Tom!!!
    Thanks for sharing. Keep it up…

  2. Great Tom! This is helping me out with one of my clients here in SJ,CA. I’d love to see more posts like this!
    Thanks for sharing:)

  3. Good article, Tom. It would be worth mentioning that there are several “boilerplate” plugins available which give you a foundation for building out your plugin. These already have the folder structure and required files in place ready for you to drop in your custom code. Here’s an example of one: http://wppb.io

    Also, it’s worth mentioning plugin security. The WPScan Vulnerability Database lists hundreds of security issues that have affected plugins. https://wpvulndb.com/plugins I’m in the process of writing a guide that will help plugin authors avoid some of the more common security mistakes. You can find out more about it by signing up here: https://gumroad.com/glenscott/follow

  4. Good article. Really do agree with Connor. This gives you “flesh to the bone” instead of not knowing where to start. Keep it up!

  5. I’ve been intrigued by the idea of creating plugins for awhile. I’m mostly a word guy, but it’s pretty much impossible not to absorb a bit of coding knowledge working on the internet these days. There are some really cool and amazing plugins out there, and it would definitely be interesting to contribute more proactively.

  6. Hello Dear Author

    I have been using WordPress since last two year as a blog writer. Now I am thinking to expand my WordPress experience and thinking about to create a blog on education. Can you suggest me a theme that would be best for education blog?

    Regard
    Annabel

  7. The road to our current version of Game On—a plugin written by high school students that allows educators to “gamify” their curriculum—was plagued with missteps while the students and I bootstrapped ourselves and worked toward a stable solution for our own classroom. Our early adopters suffered the server crashes and funky behaviors along with us.

    The dust began to settle after three years of development and for the past two years we’ve built upon a pretty solid method of employing game mechanics in the classroom. I wave the wand and the students provide the magic (they write the code). Today, around 100 classrooms are powered by Game On.

    Pretty cool considering I’m a Digital Arts teacher and don’t officially teach a computer science course.

    Game On: https://github.com/TheMacLab/game-on/releases

  8. Hi Tom,

    Great article! I’ve been working on a project where a custom post type is created. However, I’ve yet to find an elegant way to use it alongside the Divi Builder.

Leave A Reply

Comments are reviewed and must adhere to our comments policy.

Get Started With Divi