Make A WordPress Plugin – Your First Plugin

FooCamp - How to Make a WordPress Plugin

FooCamp – How to Make a WordPress Plugin – Your Environment

Now that you have your environment setup correctly, let’s start coding and make a WordPress plugin, your first! I think it will be easier to follow by example, so we will be creating the first version of our FooDocs documentation plugin in this post. These are the steps we will follow:

  1. Create a new git repository.
  2. Clone the repository to our local WordPress’ plugin folder.
  3. Create a plugin file.
  4. Define our plugin class.
  5. Hook up some actions.
  6. Register a custom post type.
  7. Active and test the plugin.
  8. Commit our changes.

Create Git Repository

I am going to be using GitHub for my source control, as I love it and I think you should try it out. If you do not feel comfortable using git from the command line, then have no fear, download GitHub For Windows or Mac. Windows users can also try SmartGitHG as Matt suggested last week. I will be using GitHub for Windows for this series. Open the GitHub wesbite and sign in. Then click the create new repository link on the top right and add your new repo: Create New GitHub Repo

Clone Repo To Plugin Folder

This is an important step that can save you a lot of time down the line. You want to clone the newly created repo directly to your WordPress plugins folder located in the wp-content folder (do not create a folder for your plugin, as cloning to the base plugin folder will create this folder for you). This makes testing and code changes extremely easy, and most importantly, allows you to commit changes to GitHub as you go. Remember, you can always roll back changes at any point! clone_to

 

Alternatively, you can use the command line to do the same thing. Navigate to your wp-content/plugin folder and then type something similar:

After you have cloned it, you should find a new folder in your plugins folder. In my example it is called foodocs. Now let’s write some code!

Create Plugin File

We need a  way to tell WordPress about our new plugin. And to do that we need to create a PHP file with some specific comment headers at the top. Create a php file with the same name as your folder name. In my example I now have a blank file at the following path wp-content/plugins/foodocs/foodocs.php

Open that file in your favourite editor. The first thing we need to do is add some special PHP comments that WordPress will use to identify the plugin and all it’s information. We only care about the following for now:

  • Plugin Name – the name of your plugin.
  • Plugin URI – a url to your plugin GitHub page, or to a page sales page, or a product support page (your choice really).
  • Description – a description of what your plugin does.
  • Author – you or your company details.
  • Author URI – link to your personal or company website.
  • Version – the version number for the plugin.

More info about these headers can be found on the WordPress codex. Here is the plugin header information for FooDocs:

Now if you go to your plugins listing in your WordPress backend, you should see your new plugin in the list with all it’s details: FooCamp : our first plugin Well done, you have created your first WordPress Plugin! It does absolutely nothing, but it is still a milestone. Now would be good time to commit your changes into git. Remember: commit changes often!

Define Our Plugin Class

I have read my fair share of WordPress plugin tutorials, and usually at this point, the author would tell you to choose a unique function prefix to use in your plugin. I do not agree with this! My reason is simple: there is too high a risk that another WordPress plugin or core function will use the same prefix. Take the safer bet and wrap your functions within a class.

Defining a class for our plugin will allow us to combine all the functionality of our plugin within a single logical “component” or “object”. Read this excerpt from the Writing A Plugin article on the WordPress codex:

All the functions in your Plugin need to have unique names that are different from functions in the WordPress core, other Plugins, and themes. For that reason, it is a good idea to use a unique function name prefix on all of your Plugin’s functions. A far superior possibility is to define your Plugin functions inside a class (which also needs to have a unique name).

So come up with a unique class name and define it:

We have now defined our class, so let’s add some code to it.

In this example I am going to create 2 functions. One is the constructor, which runs when the class is instantiated (which basically means when it is created in memory), and another function that will create a simple custom post type. These functions will be empty for now:

Notice how I did not need to prefix my function name, but rather, I named it something logical like “register_custom_post_type”. You gotta love classes!

So we have defined this class called FooDocs, but it is never loaded into memory at all, so let’s instantiate it. You do this simply by calling new Your_Class_Name() after the class definition. In my example:

But to follow best practices, we need to do more than just instantiate our object. We need to assign this new object to a variable, so that you (and potentially other developers) can use it down the line. We are going to use $GLOBALS to store the class object we are creating:

Note: In the next post we will refactor this code to use another pattern, but for now, this is simple and it serves our purpose.

Hook Up Some Actions

In the FooDocs plugin, I want to create a new custom post type, so that I can capture document content. So in order to do that I need to register the custom post type. We already have a placeholder function for this, but I need to call that function at the correct time. We need to use WordPress actions to wire up everything.

So let’s hook up our register_custom_post_type function from the __construct function, as we know that will be called when a FooDocs object is instantiated (loaded into memory). The new __construct code will look something like:

There are a few things to note here:

  • We hooked up the action using the add_action function.
  • We hooked into the init action, which runs after WordPress has finished loading.
  • We pass an array as the second parameter:
    • $this is the current instance of the FooDocs object we are dealing with.
    • ‘register_custom_post_type’ is the function we will be calling within the class.
Note: Hooking up actions to functions within a class instance can be a bit tricky to get your head around at first, especially if you are used to using prefixed function names.

Register A Custom Post Type

I generated my custom post type code using my CPT code generator on my personal site. There are a couple of these CPT code generators out there now, so take your pick. If this is the first time you are registering a custom post type, then read the register_post_type codex documentation and write it from scratch.

A few things to note about this code:

  • The labels are translatable by using the __ function. We will cover this in detail in a future post.
  • We are setting a bunch of arguments when calling register_post_type, which I will not cover in this post. Read the docs.
  • We are calling the post type foodocs. I use this unique name so that it does not conflict with other custom post types that might also be called ‘documentation’.

Activate and Test Your Plugin

Note: Before you activate your plugin, remember to make sure you are running your local WordPress install in debug mode, so that you can easily pick up any errors.

Now activate the plugin.  Hopefully there are no PHP errors or warnings, and you should see a new menu item where you can manage your newly created custom post type. FooCamp : custom post type

Commit Changes To GitHub

As I said before, it is a good idea to commit changes often. I try to keep my commits quite small and group them by individual change or feature. If you have been committing changes as you go, you should have a couple commits under your belt already. Check my commits I made so far for the FooDocs plugin. FooCamp : git commits

New Terminology

Some terminology we have learned in this post:

  • class – we define a class to represent an object or concept. In our case, our class will contain the core plugin functionality.
  • instantiate  – to create an instance of our class in memory, so that we can use it.
  • constructor – a function within a class that is automatically called when we create an instance of the class.
  • action – a WordPress hook which allows us to run code at a specific time.
  • custom post type – a piece of content that is stored within WordPress other than the usual posts and pages.

Lessons Learned From Matt

Matt’s follow-up post is great this week, as he goes through troubleshooting some issues he had when registering the custom post type.

What’s Next

In the next post, we will rework the plugin code and split up different functionality into separate files. We will also make the plugin translatable and add some readme files. See you next week!

FooCamp Series Subscription

Follow along with our FooCamp Blog Series. This subscription only applies to posts in this series, not all posts on our site.
This post was written by
Brad is the co-founder and head code wrangler at FooPlugins.com. By day he writes code until his fingers ache, by night he writes code until his eyes bleed. He has no life. His life is code. Geez, what a loser ;)

10 Comments on "Make A WordPress Plugin – Your First Plugin"

  • Brad is the co-founder and head code wrangler at FooPlugins.com. By day he writes code until his fingers ache, by night he writes code until his eyes bleed. He has no life. His life is code. Geez, what a loser ;)

    Heheh

  • Paul

    Hi, the “Clone Repo to Plugin Folder” is too cryptic. How? Github says “Click on Clone in Wondows button” but there isn’t a button. Should I download and upload the zip?

    • Brad Vincent

      Just downloading the zip to your PC is not enough. You need to clone to your wp-conten/plugins directory in order to track any changes you make.

      You can also so something like this in the command shell or Git Bash:
      $ git clone https://github.com/fooplugins/foodocs.git

      I have updated the post with this option

  • Paul

    I’m sorry, you’re assuming far too much for us newbies. “Create a php file in your favorite editor”(?) – assuming I figure out how to create a php file, do I upload it to the “foodocs” folder in the wp-content folder? You say “you should see the new plugin in the WP backend” – not unless I put the file in the right folder. I’ve been so looking forward to this series, but I’ve ended up being very frustrated because you skip essential steps in your explanation. I know it’s hard to move into a total novice’s space, but please try, otherwise I’m going to have to walk away from this series and go and do something else.

  • Paul

    Ok, “Navigate to your wp-content/plugin folder and then type something similar” Type it where? I think I’m going to go and do some gardening and leave this to others. It’s way above my head. Thanks anyway.

  • Paul, last week’s article was really more about setting up your environment. You should take a look at my companion article from last week, where I gave some details on how I got my development environment set up (as a newbie — not to development in general, but plugin development.

    I will say though, that this series is not intended to necessarily be a “from the ground up” tutorial. Brad and I really are writing more directly at people with strong WordPress experience, perhaps front-end developers who want to get into plugin development as well.

    Regardless, here’s my article from last week: http://mattcromwell.com/foocamp-setting-up-my-environment/

  • Yep, I think I’ll stick to my primary work, which is – cartooning! – and leave the nuts and bolts to you guys. Thank you for sharing this info with the wider community, good on you. Check out my website.

  • Wow! FooBar, Social Wiggle, FooBox… all on one page! Are you using WP Better Security for your firewall and Coming Soon Pro for your maintenance page too!? Seems like you’re a fan.

    Also, great cartoons. You’re talented. Thanks for the support. Best of luck to you!

  • Brad, Matt – what a great way to present a tutorial with this whole take another approach review thing happening from Matt. Fantastic!

    I’m learning so much from this series, thanks guys. I really wanted a simple explanation to opening a repo in github, and now I’ve got one. Oh… the plugin tutorial is pretty good also :-)

    Trouble is, I’ve been resisting upgrading my Mac from the 10.6 OS, but in order to you the Mac git tool (and several other apps that won’t work on 10.6) I need to, and this has pushed me over the edge, (to hell with the command line), so here goes.

    Once again thanks, I’m looking forward to the next installment

  • I just found this link to other tools for working with github in windows, Mac and Linux

    http://git-scm.com/downloads/guis

Leave Your Comment