Building a Custom WordPress Plugin From Scratch Like the Pros

Building a Custom WordPress Plugin From Scratch Like the Pros

With WordPress powering 25% of the internet, you may find yourself entertaining the idea of developing your own plugin. Here's how to not suck at it.


Building a WordPress plugin from scratch is neither simple nor easy. That said, it’s completely doable even as a beginner developer! The trick is to avoid cutting corners, as good code takes proper planning. Get involved watching seasoned developers at work so you can be inspired by beautiful code. Following step-by-step tutorials like this one also helps.

After years of learning from trial and error, I’ve come a long way in my WordPress plugin developing prowess. In this post I’m going to impart to you what I’ve learned by providing an overview of what you need, how to organize your plugin, and where to go from there.

Ready to build yourself a premium quality WordPress plugin? Yes. The answer is yes. Let’s do this!

What Makes a Plugin Good?

What defines a ‘good’ plugin depends on who you ask, but for the sake of this tutorial we’re talking about its development quality.

Here’s my personal standards for what makes a WordPress plugin good:

1. It’s built for longevity.

Ideally, once you’ve launched a production-ready WordPress plugin into the wild, the code you’ve written could last for years into the future of the WordPress platform without ever touching it again.

But… how? It’s not magic, it’s learning to use WordPress standards. That’s what the phrase, The WordPress Way really means in the end.

If you follow good coding standards according to WordPress and build using WordPress’s own structures whenever possible, it will take a very big update to the core to break your plugin if it has already been working.

(IMHO, the best plugins simply tie together existing WordPress functionality in devilishly clever ways.)

2. The code is simple and easy to read.

If you struggle reading your code after not looking at it for a few days, you’re doing it wrong.

I first learned the concept of beautiful code back in 2008 when I was introduced to Ruby on Rails. The code practically reads like an actual book. You don’t need to be a seasoned developer to understand what’s going on.

That’s how easy your code should be to read – like a poetry book. Yes, even in PHP, and yes, even in WordPress. It takes time and conscious effort to achieve, and I’m still working on it myself!

Here are two tutorials on writing beautiful code, and another article explaining why it’s important.

3. It doesn’t duplicate existing features.

Now more than ever, WordPress comes with a lot of functionality.

There is a very insignificant chance that your needs are outside what it is capable of doing for you. Most plugins can be built using the power of WordPress’s existing features.

A good plugin elegantly takes advantage of all that WordPress has to offer in the way of actions, hooks, classes, and functions. More complex features that require permissions management can usually be baked right into custom post types, taxonomies, or terms – depending on what the situation calls for.

Rejoice, for gone are the days of hacking posts and pages to do strange monkey dances!

When you’re building your plugin, think about how you can creatively use what WordPress has to offer. Chances are, it’s much simpler to develop your idea than you think. It’s well worth the time it takes to plan strategically.

Should You Create Your Own Plugin?

Most of the time, you really don’t need to build a brand new plugin from scratch unless you’re doing it for the experience.

Here are the times you should go ahead and create your own plugin, according to me:

  1. When the functionality you need truly doesn’t exist in a working plugin today, or you know how you want to take an idea to the next level.
  2. When the available solutions are simply out of your budget and you feel confident enough to build an alternative.
  3. When you’re developing a theme, and keep running into functionality that should exist in a plugin instead. Here’s how to tell which code should go where.

That’s it. Those are the three real-world situations I can think of that you’d want to build a plugin on your own, from scratch.

Please note that this evaluation comes from a business point of view, weighing time versus money spent during a project with a deadline. If you’re in this for the learning experience, by all means, hack away and create exhilarating projects!

Essentials for Plugin Development

There’s a few tricks up every developer’s sleeve, and the most important one is being able to work locally on your own computer.

Here’s everything you need for an optimal local environment:

Get a Coding Editor

My favorite code editor is Atom.

Best of all, it’s open source and available on OSx and Windows.

Run WordPress Locally

There’s already a lot of tutorials on how to do this. The easiest way to get started is with MAMP, here’s how to use it to install WordPress.

* Please note: I develop using systemwide installations of Apache, PHP, and MySQL… so I can’t give specific advice on using MAMP.

Install WP CLI

WP CLI stands for WordPress Command Line Interface.

I’ve only barely tapped the surface of what WP CLI can do, and it’s already saved me loads of time while increasing my standards of work. You can install WordPress, plugins, themes, and much, much more all from the command line… but its real power will show itself in just a moment.

WP CLI is a prerequisite for the next few recommendations, so I suggest installing it right after MAMP.

It’s really easy to install. (Check it out – there’s even instructions on getting it to work with MAMP.)

Set Up Unit Tests

Well written unit tests keep your code clean, while helping you avoid big, bad bugs in production as you continue working on a project.

Here’s a digestible introduction to the concept of test driven code.

At this point, WP CLI should already be installed. The next thing you need is PHPUnit, which you can download here.

Unfortunately, creating and running unit tests is an entirely different tutorial, so for now I’ll leave you with Pippin’s Guide to Unit Tests for WordPress.

Lint Your Code

Besides running unit tests, my favorite part of the WP CLI is being able to clean my code automatically.

You can install what’s called a code linter, which will tell you when you’re breaking WordPress coding standards. Often times, it can fix a lot of them automatically for you.

Here’s how to install it in your command line:

wp package install frozzare/wp-cli-lint

Within your project, all you have to do is run:

wp lint

Here’s a condensed version of what kind of messages you may receive:

FILE: ...-content/plugins/autoupdates-standard/library/class.projects.php
----------------------------------------------------------------------
FOUND 39 ERRORS AFFECTING 33 LINES
----------------------------------------------------------------------
  5  | ERROR | [x] Tabs must be used to indent lines; spaces are not
     |       |     allowed
     |       |     (Generic.WhiteSpace.DisallowSpaceIndent.SpacesUsed)
  7  | ERROR | [x] Tabs must be used to indent lines; spaces are not
     |       |     allowed
  36 | ERROR | [x] Tabs must be used to indent lines; spaces are not
     |       |     allowed
     |       |     (Generic.WhiteSpace.DisallowSpaceIndent.SpacesUsed)
----------------------------------------------------------------------
PHPCBF CAN FIX THE 39 MARKED SNIFF VIOLATIONS AUTOMATICALLY
----------------------------------------------------------------------

That line at the end? That means it’ll clean your code right on up if you run:

phpcbf --standard=WordPress *

Sometimes, it’s an error you’ve got to fix on your own. The WP Lint tool is how I learned to start using Yoda conditions.

FILE: ...wp-content/plugins/autoupdates-standard/library/class.tables.php
----------------------------------------------------------------------
FOUND 1 ERROR AFFECTING 1 LINE
----------------------------------------------------------------------
 297 | ERROR | Use Yoda Condition checks, you must
     |       | (WordPress.PHP.YodaConditions.NotYoda)
----------------------------------------------------------------------

Plan Your Plugin Before You Code

Believe it or not, code is a bit like golf. Winning means you did as little of it as possible, in the fewest strokes.

In the same way that a professional golfer spends a lot of time strategically measuring the elements before ever swinging their club, you’ve got to plan your approach to code before you proverbially step foot on the course.

If you plan it well, actually coding the plugin should be where you spend the least amount of time. Hypothetically.

Start On Paper

Outline the detailed functionality of your plugin.

What does it do? What features does it need? Which users can add or delete things? Which users can see them at all?

Think through everything you want from your plugin. Consider every element that your plugin is going to need. Write it all down.

Organize the similar bits together.

You’ll wind up with a lot of scattered notes, so now you’ve got to start grouping together the bits that are related to each other.

As you work, think in terms of WordPress. What functionality fits this best? Would it work as a custom post type? A new taxonomy? Is it a widget? Are you making really custom database queries, or can you use get_posts()?

Start developing the logic.

This is the hardest part: you must pretend to code your plugin without actually coding it. Code on paper, if it helps.

The point is learning how to solve problems pragmatically without getting caught up in bug fixing or syntax errors. Put your plugin together piece by piece, thinking through the logic it needs to work. Identify which data you need to to communicate to WordPress, and which data you’ll need to collect from WordPress. How will you do that?

To find the answer, start researching specific WordPress techniques.

If you can’t find what you need, Google specific bits and pieces. You may be surprised what people have already experimented with! Bookmark the tutorials and code snippets that seem relevant to your project.

It’s okay to take some time to work through tutorials as you research, if things get too confusing. It’s all part of the process. Ultimately, you’ll be better informed and come up with stronger solutions.

P.S. If you don’t use object-oriented programming yet, I highly recommend you start now. Here’s a quick-start guide, followed by an entire WordPress OOP course.

Plan out your project structure.

Everything is starting to come together, but you should also consider how you’ll organize the actual files for your project.

Here’s how I organize my plugins these days:

/plugin-slug
	plugin-slug.php
	/admin          # admin settings pages
	/assets         # images, styles, scripts
		/css
		/img
		/js
	/library        # all classes and other files
		class.example.php
	/tests          # unit tests

Finally, Start Coding

By now, your plugin should have already taken some definitive shape before you even opened the code editor. Remember? I told you I wanted to teach you how to build plugins like the pros, not hack together a makeshift plugin that fails under pressure.

Before you get started on your code, always remember to work using the two following rules.

Don’t Repeat Yourself (DRY)

WordPress has many, many functions that already do a lot of what you need. Not all of it is well documented in the Codex, but it’s in there if you search hard enough.

For example, I started trying to build my own slug sanitization function to enable custom permalinks for a custom post type I was building, when I realized WordPress must have one of its own. About 15 minutes later, and I was happily using the built-in function sanitize_title().

Before spending a lot of time on complicated custom functions, triple check whether it’s out there already.

Build on the framework, not next to it.

As stated before, WordPress is packed with amazingly powerful and flexible tools.

To create a good plugin, you should always work within the framework as much as possible. It can make the difference between paddling hard up stream all day to reach your bare minimum goals, and being able to start your own logging company by floating easy with the current and being able to focus on the quality of your lumber instead of whether the ship will sink. (Sorry, another random comparison, I know.)

The moral of the story is, let the easy things be easy.

Use custom post types, taxonomies, meta data, and all the other goodies of WordPress to your advantage. Focus your effort on what makes your plugin clever and unique.

Barebones Plugin Requirements

Welcome to your plugin. WordPress has a few minimum requirements before you can activate it in the admin.

First, make a folder in your local WordPress plugins folder – /wordpress/wp-content/plugins – with your desired ‘slug’. Something like, /wp-dictionary.

Inside your folder, create a .php file that has the same ‘slug’ as the folder you just created – something like wp-dictionary.php.

At the top of that file, you’ll insert some basic information about your plugin. Here’s a stripped down example of what I use for my Dictionary Plugin:

<?php
/*
Plugin Name: Dictionary Plugin for WordPress
Plugin URI:  https://www.annedorko.com/wp-dictionary
Description: Easily build your own custom dictionary with WordPress!
Version:     2.4
Author:      Anne Dorko
Author URI:  https://www.annedorko.com/

Congratulations!

From here on out, all you have to do is implement the logic you designed earlier. Just remember, writing code is more of a marathon than a sprint.

Build your plugin piece by piece, testing each new element along the way with those unit tests we talked about earlier. Sooner than later, you’ll find yourself sitting on a pretty quality WordPress plugin that does what you expect, when you expect it to.

If you can successfully do that, not only are you sitting on some great software, but you have seriously improved your development skills, which I hear translates well in the job market.

Not too shabby, eh?

Where are all the code examples?

There’s a million tutorials explaining the details of creating a folder, adding files, and activating a ‘Hello World’ plugin in WordPress.

All it takes is a quick search to find out how to throw together some files that call themselves a WordPress plugin. This tutorial is about the proper development strategy behind really building a plugin that works and will last a long time into the future.

Depending on whether this post spawns questions, I’d love to get more into the actual process of coding, testing, and publishing a plugin – but the use cases are so specific that I’d need to see what people are interested in learning.

In Review

There’s a lot covered in this post, and honestly it could easily be turned into an entire course itself.

Here’s what was covered to help you plan and execute a WordPress plugin just like the pros:

  1. Get to know what ‘good’ coding really means for WordPress.
  2. Determine whether you need to build a plugin from scratch.
  3. Set up your computer to edit code, run WordPress locally, run unit tests, and automatically clean the presentation of your code.
  4. Develop the logic for your plugin without writing code on your computer.
    • Bonus: Get familiar with object-oriented programming.
  5. Finally, put your plugin together with actual code.

I’m almost afraid to ask… but, any questions? Leave them in the comments and I’ll be here to help! What plugin ideas are you trying to build, and what’s stopping you?

Meanwhile, if you know any developers looking to level up their skills lately, please take a moment to share it with them.