- 15 minute read
- WordPress, Plugins, Essentials
- Sharing on Twitter, LinkedIn
WordPress plugins are PHP scripts that modify your website. Changes can be anything from the simplest tweak in the header to a more drastic makeover (such as changing the way logins work, enabling email sending, and much more). (This article was revised and updated on July 5, 2017.)
While themes change the look of your website, plugins change how it works. With plugins, you can create custom post types, add new tables to your database to track popular articles, automatically link your content folder to a “CDN” server like Amazon S3…you get the picture.
Theme Or a plugin?
If you’ve ever played with a theme, you’ll know that it has a functions.php file, which gives you a lot of power and allows you to create plugin-like functionality in your theme. So if we have this functions.php file, what’s the point of a plugin? When should we use one and when should we create our own? The line here is blurrier than you might think, and the answer will often depend on your needs. If you just want to modify the default length of your post excerpts, you can safely do so in functions.php. If you want something that allows users to message each other and become friends on your website, then a plugin will suit your needs better.
The main difference is that a plugin’s functionality persists regardless theme you’ve enabled, while any changes you’ve made to functions.php will stop working once you switch themes. Also, bundling related functionality into a plugin is often more convenient than leaving a lot of code in functions.php.
Creating our first plugin
To create a plugin, everything What you need to do is create a folder and then create a single file with one line of content. Navigate to the wp-content/plugins folder and create a new folder called Awesomeplugin. Inside this new folder, create a file called awesomeplugin.php. Open the file in a text editor and paste the following information into it:
– a plugin to create awe and spread joy Version: 1.2 Author: Mr. Awesome Author URI: https://mrtotallyawesome.com License: GPL2 */ ?>
Of all this information, only the name of the plugin is required. But if you intend to distribute your plugin, you should add as much data as possible.
With that out of the way, you can go to the back-end to activate your plugin. That’s all about it! Of course, this plugin does nothing; but strictly speaking, it’s an active, functional plugin.
Structuring Plugins
When creating complex functionality, it can be easier to split the plugin into multiple files and folders. The choice is yours, but following some good advice will make your life easier.
If your plugin focuses on a main class, put that class in the main plugin file and add one or more separate files for another functionality. If your plugin enhances the WordPress back-end with custom controls, you can create the usual CSS and JavaScript folders to store the appropriate files.
In general, look for a balance between layout structure, usability and minimalism. Split your plugin into multiple files as needed, but don’t overdo it. I find it helpful to look at the structure of popular plugins like WP-PageNavi and Akismet.
Naming Your Plugin and Its Functions
When creating a plugin, be careful when naming the functions, classes, and plugin. per se. If your plugin is for generating awesome excerpts, calling it “excerpts” and calling its main function “the_excerpt” might seem logical. But these names are too generic and can clash with other plugins that have similar functionality with similar names.
The most common solution is to use unique prefixes. You could use “acme_excerpt”, for example, or anything else that is unlikely to match someone else’s naming scheme.
Plugin Security
If you plan to distribute your plugin , then security is of the utmost importance, because now you are playing with other people’s websites, not just your own. All of the security measures you should take deserve their own article, so keep an eye out for an upcoming article on how to secure your plugin. For now, let’s look at the theory in a nutshell; you can worry about the implementation once you understand that.
The security of your plugin generally depends on the stability of its two legs. One leg makes sure the plugin doesn’t help spread mischievous data. Protecting against this involves filtering user input, avoiding queries to protect against SQL injection attacks, etc. The second leg ensures that the user has the authority and intent to perform a given action. Basically, this means that only users with the authority to delete data (such as administrators) should be able to do so.Taking care of the intention ensures that visitors are not tricked by a hacker who has managed to place a malicious link on your website.
All of this is much easier to do than you think, because WordPress offers you many functions. to handle it. However, there are other issues and best practices involved, so we’ll cover them in a future article. There is much to learn and do until then; if you’re just getting started, don’t worry about all that for now.
Cleaning Up After Yourself
Many plugins are guilty of leaving a lot of unnecessary data lying around. Data only used by your plugin (like metadata for posts or comments, database tables, etc.) can end up as dead weight if the plugin doesn’t clean up after itself.
WordPress offers Three great hooks to help you take care of this:
- register_activation_hook()This hook allows you to create a function that runs when your plugin is activated. It takes the path to your main plugin file as the first argument and the function you want to execute as the second argument. You can use this to check your plugin version, do some cross-version upgrades, check for the correct PHP version, etc.
- register_deactivation_hook()The name says it all. This function works like its older counterpart, but is executed every time your plugin is deactivated. I suggest using the following function when deleting data; use this one for general cleanup only.
- register_uninstall_hook() This function is called when the website admin removes your plugin in the WordPress backend. This is a great way to remove data that has been lying around, such as database tables, configurations, and so on. One drawback to this method is that the plugin must be able to run for it to work; so if your plugin cannot be uninstalled this way, you can create an uninstall.php file. See the documentation for this feature for more information.
If your plugin tracks the popularity of content, it may not be prudent to delete the tracked data when the user deletes the plugin. In this case, at least direct the user to the location on the backend where they can find the plugin data, or give them the option to delete the data on the plugin settings page before removing the plugin itself.
The net result of all our effort is that a user should be able to install your plugin, use it for 10 years, and then remove it without a trace in the website, database, or file structure.
Documentation and coding standards
If you’re developing for a large community, documenting your code is considered good manners (and good business). The conventions for this are pretty well established: phpDocumentor is an example. But as long as your code is clean and you have some documentation, you should be fine.
I also document the code for my own benefit, because I barely remember what I did yesterday, let alone the purpose of the functions. that I wrote months ago. By documenting code, you enforce good practices on yourself. And if you start working on a team or your code becomes popular, documentation will be an inevitable part of your life, so you better start now.
Although it’s not as important as documentation , following coding standards is a good idea if you want your code to comply with WordPress guidelines.
Putting it into practice
All work and no play makes Jack a Boring boy, so let’s do something with all this knowledge we just gained. To demonstrate this, let’s build a quick plugin that tracks the popularity of our articles by storing how many times each post has been viewed. I’ll be using hooks, which we’ll cover in a future installment of this series. Until then, as long as you understand the logic behind them, all is well; You’ll understand hooks and plugins in no time!
Planning Ahead
Before writing any code, let’s think ahead and try to determine what features our plugin will need. This is what I came up with:
- A function that logs a view every time an individual post is displayed,
- A function that allows us to retrieve the raw number views,
- A function that allows us to display the number of views to the user,
- A function that retrieves a list of posts based on their view count.
Preparing our function
The first step is to create the folder and file structure. Putting all this in one file will be fine, so let’s go to the plugins folder and create a new folder called awesome_popular. In this folder, create a file called awesomely_popular.php. Open your new file and paste some metadata on top, something like this:
Recording Post Views
Without going too deep, WordPress hooks allow you (among other things ) trigger one of your functions every time another WordPress function is executed.So if we can find a function that runs every time an individual post is viewed, we’re all set; all we would have to do is write our own function that records the number of views and hook into it. Before we get to that though, let’s write the new function itself. Here’s the code:
As you can see, I’ve added phpDocumentor-style documentation to the top of the function, and this is a pretty good indication of what to expect from this convention. First, using a conditional tag, we determine if the user is viewing a post on a dedicated page.
If the user is on a dedicated page, we extract the $post object, which contains data about the post that is displayed (ID, title, publication date, number of comments, etc.). We then retrieve the number of views the post has already gotten. We’ll add 1 to this and then overwrite the original value with the new one. In case something goes wrong, we first check if the current view count is what it should be.
The current view count should be set; it cant be empty. And it needs to be numeric so we can add 1 to it. If it doesn’t meet these criteria, we can safely bet that the current view count is 0. We then add 1 to it and save it to the database. Finally, we return the number of views the post has gotten, along with this last number.
So far, so good. But this function is never called, so it won’t actually be used. This is where the hooks come in. You can access your theme files and call the function manually from there. But then you would lose that functionality if you ever changed the theme, thus defeating the whole purpose. A hook, called wp_head, which runs just before the tag is present in most themes, so we can set our function to run whenever wp_head is run, like so:
add_action(“wp_head”, “awepop_add_view “);
That’s all there is to the “mysticism” of hooks. Basically, we are saying that whenever wp_head is called, also call the awepop_add_view function. You can place the code before or after the function itself.
Retrieving and displaying the views
In the function above, I already use the WordPress get_post_meta() function to retrieve the views , so writing a separate function for this might seem a bit redundant. In this case, it might as well be redundant, but it promotes object-oriented thinking and gives us more flexibility when developing the plugin further. Let’s take a look:
This is the same snippet we used in the awepop_add_view() function, so you could use it to retrieve the view count there as well. This is useful, because if you decide to handle case 0 differently, you just need to change it here. You’ll also be able to easily extend this and provide support for cases where we’re not aware of (ie when the $post object isn’t available).
So far, we’ve only retrieved the view count . Now let’s show it. You might be thinking this is nonsense: all we need is echo awepop_get_view_count() . “views”, right? That would certainly work, but what if there is only 1 view? In this case, we would need to use the singular “view”. You may also want the freedom to add some initial text or some other detail, which would be difficult to do otherwise. So, to allow for these scenarios, let’s write another simple function:
Display a list of posts based on views
To display a list of posts based on view count, we create a function that we can place it anywhere in our theme. The function will use a custom query and loop through the results, displaying a simple list of titles. The code is below and the explanation follows.
We start by passing a bunch of parameters to the WP_Query class, to create a new object to hold some posts. This class will do the heavy lifting for us: it finds 10 published posts that have awepop_views in the meta table and sorts them according to this property in descending order.
If the posts meet this criteria, we create an element of unordered list. We then loop through all the posts we’ve retrieved, displaying each title as a link to the relevant post. We finish things off by adding a closing tag to the list when there are posts to display. Placing the awepop_popularity_list() function anywhere in your theme should now generate a simple list of posts sorted by popularity.
As an added precaution, place the call to this function in your theme, like this:
if (function_exists(“awepop_popularity_list”)) { awepop_popularity_list(); }
This ensures that if the plugin is disabled (and thus the function becomes undefined), PHP will not throw a huge error. It just won’t display the list of the most popular posts.
Overview
By following the theory laid out in this article and using only a handful of features, we’ve created a rudimentary plugin for tracking our most popular posts. It could be improved a lot, but it perfectly shows the basics of using plugins.Also, by learning some WordPress development patterns (plugins, hooks, etc.), you’re gaining skills that will serve you well in non-WordPress environments as well.
You should now be able to follow through tutorials with confidence. that start with “First, create a WordPress plugin…”. You now understand things not just based on what you need to know, but at a deeper level, giving you more flexibility and power when coding your own plugins. Stay tuned for the next article on Hooks, Actions, and Filters for an even more detailed resource on the ins and outs of plugins.
Further reading
- Ten things about every plugin WordPress Developer should know
- How to create a WordPress plugin that uses service APIs
- How commercial plugin developers are using the repository
- How to improve the Readme.txt file of your WordPress plugin
.