WordPress Development for Intermediate Users: Building Plugins
Plugins let you add or change how your sites looks or functions. And the best part? Just about any kind of functionality you can dream up for your site, you can turn into a plugin and make it happen.
This is the third post in our WordPress Development for Intermediate Users series. This series follows on from our popular WordPress Development for Beginners tutorials, which introduced you to the fundamentals of developing websites with WordPress, how to get started coding with PHP, and building themes and plugins.
You should already know how to create a basic plugin – if you don’t, you should review our beginners series before proceeding – so I’m not going to show you how to do that. Instead, we’ll look at how to build some more complex plugins as well as best practice for plugin development.
So far in this series, you’ve developed a theme, including template files, hooks and Customizer functionality. In this part of the course, we’ll make use of one of the hooks you’ve already added, and insert content by hooking into it.
Note: It’s important that you have a working knowledge of PHP as this is the foundational language of WordPress and I’ll be referring to code snippets throughout this series.
Let’s get started.
Missed a tutorial in our WordPress Development for Intermediate Users series? You can catch up on all seven posts here:
- WordPress Development for Intermediate Users: Theme Development in Detail
- WordPress Development for Intermediate Users: Making Your Themes Customizer-Ready
- WordPress Development for Intermediate Users: Building Plugins
- WordPress Development for Intermediate Users: Custom Post Types and Taxonomies
- WordPress Development for Intermediate Users: Queries and Loops
- WordPress Development for Intermediate Users: Custom Fields and Metadata
- WordPress Development for Intermediate Users: Internationalization
That’s right, tons of WordPress knowledge, peer review, instructor feedback and certification, for free for WPMU DEV members
What You’ll Need
To follow along with this part of the series, you’ll need a development site with a theme installed and activated. As we’ll be interacting with the theme from the earlier parts of the series, you’ll need to use that theme. If you’d rather work with your own theme, you’ll have to add a hook to that using the techniques you learned in the first part of this series.
If you’ve been working along, you’ll have your own version of the theme for this series. If not, you can download the theme from part two, WordPress Development for Intermediate Users: Making Your Themes Customizer-Ready, which is in the source files for this course.
You’ll also need a development site to work with (maybe on your local machine) and a code editor.
Best Practices for Plugin Development
Before we start creating some plugins, let’s take a look at how you should be coding your plugins. To be a competent and efficient plugin developer, you should follow best practice:
- Structure your plugin files and folders appropriately. Your plugin needs a main plugin file and if you need to add any additional files you should add them to appropriate folders, such as folders for scripts, styles, templates and includes.
- Use the right hooks. Don’t attach a function to a hook that fires too early or too often for your needs.
- Use DRY principles, avoiding repetition in your code. Where code needs to be repeated in multiple places, use an include file instead so you only have to code it once.
- Don’t create functions, classes or hooks that duplicate functions already provided by WordPress. Familiarize yourself with WordPress functions, classes and hooks so you can make best use of them.
- Don’t use deprecated functions.
- If you need to use scripts or styles in your plugin, enqueue them properly (more of which shortly).
- Use correct (and consistent) syntax and write your code in the way outlined by the coding standards, with liberal use of comments to help yourself and other users.
- When creating your own hooks and functions, use prefixes to ensure they have unique names. In this course I’m using
wpmu_as a prefix throughout.
Whatever kind of plugin you’re developing, following these tips will make your code and working practices more efficient, and will help you get your plugins accepted for release in the WordPress Plugin Directory.
Adding Scripts and Styles to Plugins
In many cases, you’ll need to add scripts and styles to your plugins. It’s important to know how to do this correctly. Instead of using an include call or attaching scripts or styles to the
wp_footer hooks, you should use the correct functions and hooks for enqueueing your styles and scripts.
To do this you need one of two hooks:
wp_enqueue_scripts– for scripts and styles that will be used in the front end of your site
admin_enqueue_scripts– for scripts and styles that will be used in the admin screens
In most cases you’ll be using the first of these. But if you want to brand the admin screens by adding a new stylesheet, for example, or you want to add a date picker to a widget’s form in the admin screens, then you’ll need to use
admin_enqueue_scripts. Note that you use these two hooks for both scripts and styles – there isn’t an equivalent hook with the word styles in it.
To tap into one of these hooks, you’ll need to create a function that does two things:
- registers a script or stylesheet (
- enqueues it (
These are the same whether the script or style is hooked to the front-end hook or the admin hook. Sometimes you only need to enqueue a script, if it’s already bundled with WordPress – jQuery, for instance.
Here’s an example of how you’d enqueue a script in a plugin to be used in the admin screens. This script is dependant on jQuery:
register_script() function has three parameters in this example:
- The unique name of my script, which I then use when enqueuing it.
- Its location, which is relative to the current file.
- A dependency (optional), which is jQuery.
Registering a stylesheet in a plugin is similar and you’ll get a chance to do that as you work through this part of the course.
Note that enqueueing scripts and styles to your themes is very similar except for one key difference: the location will be different. Instead of using
plugins_url(), you use
get_template_directory_uri() with the subdirectory and file listed after that. So if you were enqueuing the same script I’ve loaded above in a theme, you’d code it like this:
For full guidance on this see our guide to adding scripts and styles to WordPress the right way.
Uses for Plugins
You can use a plugin to add just about any kind of functionality to your site. While we’ve already looked at the functions.php file in your theme, and added Customizer functionality to the theme via an include file, you should normally be writing a plugin to add functionality. Themes are for design and display: they define how your site displays its content, while your plugins will add extra functionality for adding content or managing the site.
The general rule of thumb is to ask yourself this question?
If I switch themes for my site, will I still need this functionality?
If the answer is yes, then write a plugin instead of coding it in your theme. So you might write a plugin to do any of the following:
- Register custom post types or taxonomies.
- Add a custom metabox to your post editing screens.
- Create a widget.
- Insert content via a hook (e.g. a call to action button or custom query).
- Create a shortcode.
- Add admin customization such as extra help text or admin screens.
- Pull in content from an external source using an API.
- Create a custom template to display content added by the plugin (not just to replace a theme template file).
- Add custom display such as a gallery.
- Maximise performance, enhance SEO and/or increase security.
You’ll find many of these available in fantastic third party plugins, including our own, so it’s worth checking those out before you code your own. Another option is to take a third party plugin and edit it to meet your needs. There are quite a few plugins in the plugin directory that have started life this way.
Note that there isn’t a child/parent system for plugins as there is for themes, so once you fork a plugin, you’ll be responsible for maintaining the code. Alternatively, you could create another plugin that makes use of the hooks provided by the third party plugin – I do this quite a lot when I want to customize WooCommerce, which is full of hooks.
Now, let’s create some plugins. I’m going to walk you through the process of creating three plugins:
- A shortcode plugin
- A widget plugin
- A content plugin to hook to your theme
Building a Shortcode Plugin
Shortcodes are blocks of text you place in square brackets in your posts and pages to add content that’s predefined by the shortcode. These take three forms:
- Simple shortcodes that insert predefined content: [shortcode]. For example, you might create a shortcode with the markup for a call to action button and add that to posts and pages using the shortcode.
- Shortcodes with opening and closing tags and content between them: [shortcode]content[/shortcode]. You might use a shortcode like this to add markup around the enclosed content, as we do here on the WPMU DEV blog.
- Shortcodes with parameters: [shortcode parameter=”value”]. Shortcodes can have as many parameters as you want. An example here might be if you’re adding a shortcode to insert markup but letting the user vary it via the parameters.
Let’s explore all three of these options by creating a shortcode for a call to action button.
Creating the Plugin
Start by creating an empty plugin file in your wp-content/plugins directory and adding the opening text to it. You learned this in detail in the beginners’ development series. As we’ll be adding some styles, you’ll need to create a folder for your plugin. Activate the plugin on your development site.
Save and activate your plugin.
Create a folder called css in your plugin folder and inside that, a file called style.css. Now open your main plugin file and add this to it:
This will enqueue the stylesheet for the call to action box. The styles are as follows: you can add these to your plugin’s style.css file or create your own:
Creating a Simple Shortcode
Let’s start by coding a simple shortcode that outputs predefined markup and text when it’s added to a page or post.
In your plugin file, add a function to create the shortcode:
You’ve created a function with the markup to display the shortcode contents, and then used the
add_shortcode() function to turn that into a shortcode. The
add_shortcode() function has two parameters:
- the text a user types inside square brackets to insert the shortcode
- the callback function to run when the WordPress comes across the shortcode.
Now go to a page or post in your site and type [cta-simple]:
Save the post or page and view it. Here’s mine:
You can see that the box is showing up but that it’s not in the place where I added the shortcode when I was editing the post. Instead it’s been inserted at the beginning of the content. We fix that using a couple of PHP functions:
Edit your function so it looks like this:
Now check your page. The box should show up in the right place:
That’s better! So we now have a shortcode. But what if the user wants to change the text that’s displayed? We can do that by creating a different kind of shortcode: one with opening and closing tags.
Creating a Shortcode with Opening and Closing Tags
In your plugin file, create a new function like this:
This adds some parameters to our callback function:
$atts, which isn’t used but is necessary for the second parameter to work, and
$content, which is the content a user types in between the tags.
Now in your page or post’s code view, type in the shortcode as follows:
Save the post/page and view it. It will show the call to action box with whatever content you added:
This means that your users can type whatever content they like inside that call to action box. But now let’s make things even simpler for them.
Creating a Shortcode with Parameters
There’s a good chance that someone using your shortcode won’t feel comfortable coding the markup for the link inside it. So let’s create a more advanced shortcode with two attributes: telephone and email.
In your plugin file, create a third function, like this:
Now enter the shortcode in your page with the attributes. Something like this:
Update the post or page and take a look at it on the front-end. The call to action box will show up using the values you’ve given for those attributes:
So you can see how adding attributes to a shortcode can make things a bit easier for users, and save them having to write code, while giving them more control over what’s output. You could use this technique in a variety of ways to control, content, code and styling.
Building a Widget Plugin
Another common use of plugins is to create a widget that users can add to a widget area in their site. Let’s use the code from our shortcode plugin to create a widget for the call to action button.
Creating the Widget
To create a widget you need to interact with the
WP_Widget class, which is part of the Widgets API. There are four elements to coding a widget, which go inside your class:
- The function to construct the widget
- The form for widget admin
- A function to process updates to widget settings
- A function to output the widget on the site.
You then need to register the widget using
Let’s start by coding the empty widget class and registering it.
Create a new plugin, with its own folder in your wp-content/plugins directory. Create a file for css and a stylesheet in that folder, as you did with the shortcode function. You’ll need to edit the styling so it looks better in a widget area – the main difference will be the width, which will need to add up to 100% when you factor in margins and padding – and also to target the widget area and not the shortcode (you’ll see the classes once you start writing the widget code).
I’m not going to tell you how to do this as it’s the sort of thing you should be able to work out by this stage of the course, but you can find my code in the source code for this course.
Enqueue your stylesheet in your plugin as you did for the shortcode plugin – make sure you don’t use the same function name for enqueueing, as that will trigger an error.
Here’s my code for the plugin so far:
Don’t save your file just yet, as it won’t work without the contents of that class.
Creating the Constructor Function
The first function inside that class is a constructor function. Let’s create it. Inside your class, add this:
That constructs the widget: it defines its class name and its description. Now let’s move on to the form for the widgets screen.
Still inside your class, add the following:
This does the following:
- It defines three variables: the title, telephone number and email.
- It outputs a form with the input fields for each of our three variables.
So now we have a form in the Widgets screen. But it won’t actually do anything yet.
Saving Inputs to the Widget
To save what a user inputs to those fields for our widget, we need to create an input function that saves them to the database.
Under the function you just added, add this:
This uses the
$instace variable to store an array of values, one for each of our fields. In each case it checks if something new has been input and if so, saves that as the new value, replacing the old one.
Outputting the Widget on the Site
The final step is to output the widget on the site, in the widget area the user adds it to.
Still inside your class, add this:
You should recognise some of the code in there, as it’s similar to the code we used to output the call to action box when we created the shortcode plugin. Again youwe’veve defined variables based on the value of each element in the array for the
$instance variable. This is then output in a call to action box, with text and a link added.
That’s it! Now save your plugin and make sure it’s activated on the site. Here’s the full class that you’ll have created:
Now if you add the widget to a widget area and input the email and phone number, it will display in your site. Here’s mine in the sidebar:
You can use this technique to create a widget to display anything you wanted, and use those variables and form fields to define text, classes or anything else.
Building a Plugin to Hook to Your Theme
Now let’s move onto another kind of plugin. Instead of displaying this plugin’s contents via a shortcode or a widget, we’re going to attach it to a hook in the theme.
Again we’ll create a call to action box but this time we’ll insert it below the content of each post using a function and a conditional tag. It will only appear on single posts, not in pages or archive pages.
Start by creating a new plugin, again with a stylesheet that you need to enqueue in the plugin file. You’ll need to amend the classes in the stylesheet to reflect the classes used in the plugin’s output code, which you’ll see as we go along.
For this to work with your theme, you need to either be running the theme we developed in parts one and two of this series (which you can find in the source files) or to add a hook below the content in your own theme. The name of our hook is
Once you have your plugin set up, start by adding the empty function and the hook:
Now inside that function add the
is_singular() conditional tag:
Next, inside that conditional tag, add the code to output the call to action box:
Save your file and activate the plugin. Here’s the full function and hook:
Now when you view a post in your site, you’ll see the call to action box at the bottom:
So now you have the call to action box output on pages and not posts or archives (check it on your site!).
It’s worth noting that the call to action box we’ve been working with could be added via the Customizer. You could add a section to the Customizer for the call to action box, create controls and settings for the telephone number and email address, then hook the output to the
after_content hook. You could even add a radio button asking users to select which content type the box should appear under. As an extra challenge, why not try doing that? You can use a combination of the techniques you’ve learned here and those you learned in the previous part of this series.
Plugins Come in Many Forms
As you’ve seen from working through a few example plugins, there are different types of plugin that display content in your site in varying ways. These are all simple plugins, outputting simple code and with practice, you’ll start creating much more complex plugins to create and output content in ways that your users can define.
But plugins aren’t just about displaying content – you can create a plugin to help you with site admin or to improve your site’s performance, among many other uses. As we continue working through this course you’ll find yourself coding more plugins that do different jobs.
In the next part in this series, we’ll move on to work with custom post types and taxonomies. You’ll learn how to register them and display them via the relevant theme template files. See you next time!
WIN a Share of $5K
Subscribe to our blog this #hostingmonth for a chance to win one of 5 prizes of $1,000 WPMU Dev credit! Learn More.