Académique Documents
Professionnel Documents
Culture Documents
WordPress Plugins allow users to easily modify, customize, and enhance any WordPress
website. Instead of changing the core software WordPress is built on you can rather create a
plugin to extend it. Using plugins allows you to have the most optimized WordPress
installation all while maximizing how you use the software to begin with.
This article will walk you through the steps in creating a WordPress plugin.
Creating a Plugin
When creating a WordPress plugin there are some standards to uphold to when doing so.
Below Ill outline some key points to remember when creating your own.
Plugin Name
If youre planning on making a plugin that doesnt exist yet you will need to first determine its
name. To be extra sure you will want to do a search in the WordPress Plugin repository.
Some developers choose a name that describes more of what the plugin does so the end
user can establish a quick connection with the name. The name itself can be multiple words.
Plugin Files
Typically a plugin lives within its own folder under wp-content/plugins/ inside your
WordPress installation. There is usually at least one PHP file that is typically named after the
plugin. So if your plugin was named amazing-plug then your PHP file name would most likely
be amazing-plug.php. Using a unique name is crucial so no two plugins use the same
name.
You can also choose to split your plugin into multiple files; similar to the way WordPress is
built. Assets such as images, CSS, and JavaScript are common to see within installed
plugins.
Readme File
Readme files are useful for other developers and users. Usually these files give a quick
description of the plugin as well as sometimes offer change logs which indicate previous
updates and maintenance announcements to users.
Home Page
If you plan to share you plugin with the WordPress community, having a dedicated home
page would be wise. This page can be used as a place to download the plugin, report bugs,
and announce updates to your user community.
The minimum WordPress needs to establish your file as a plugin is the line
Plugin Name: My Plugin Name
The rest of the information will be displayed within the Admin area under the Pluginssection.
Plugin Scope
Our plugin will start with a simple PHP file. We will call this file custom-musicreviews.php. Within our file we will create a custom post type as well as define some new
categories within that post type. The purpose of this plugin will be to write music reviews
within specific genres without needing to touch code in the future. Each review will have a
feature image, excerpt, rating, and genre type.
Starting Off
Assuming you have a local copy of WordPress ready to use, navigate to your wpcontent folder inside of a code editor of your choice. Inside that folder you should see a
folder called plugins. Inside of that folder create a new folder called custom-musicreviews.
With the folder created create a new file inside it called custom-music-reviews.php.
The path to the file should now be wp-content/plugins/custom-musicreviews/custom-music-reviews.php.
With your new file created we need to add some parameters in comment form like I explained
earlier. For our plugin our parameters will look like this:
<?php
/**
* Plugin Name: Custom Music Reviews
* Plugin URI: http://elegantthemes.com/
* Description: A custom music review plugin built for example.
* Version: 1.0
* Author: Andy Leverenz
* Author URI: http://justalever.com/
**/
With this information added, save your file and navigate to your WordPress admin area. Click
on Plugins on the left side navigation and you should now see our plugin available. Wasnt
that easy?
With our parameters in place our plugin becomes available to activate under Installed Plugins.
Even though our file is empty we can go ahead and activate the plugin. Go ahead and do that
now. Youll hopefully notice nothing different about your site with the plugin activate. If you do
you probably typed the content above wrong or failed to close the comment.
function register_cpt_music_review() {
$labels = array(
'name' => _x( 'Music Reviews', 'music_review' ),
'singular_name' => _x( 'Music Review', 'music_review' ),
'add_new' => _x( 'Add New', 'music_review' ),
'add_new_item' => _x( 'Add New Music Review', 'music_review'),
'edit_item' => _x( 'Edit Music Review', 'music_review' ),
'new_item' => _x( 'New Music Review', 'music_review' ),
'view_item' => _x( 'View Music Review', 'music_review' ),
'search_items' => _x( 'Search Music Reviews', 'music_review'),
'not_found' => _x( 'No music reviews found', 'music_review'),
'not_found_in_trash' => _x( 'No music reviews found in
Trash', 'music_review' ),
'parent_item_colon' => _x( 'Parent Music Review:','music_review' ),
'menu_name' => _x( 'Music Reviews', 'music_review' ),
);
$args = array(
'labels' => $labels,
'hierarchical' => true,
'description' => 'Music reviews filterable by genre',
'supports' => array( 'title', 'editor', 'author','thumbnail', 'trackbacks'
, 'custom-fields', 'comments', 'revisions','page-attributes' ),
'taxonomies' => array( 'genres' ),
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 5,
'menu_icon' => 'dashicons-format-audio',
'show_in_nav_menus' => true,
'publicly_queryable' => true,
'exclude_from_search' => false,
'has_archive' => true,
'query_var' => true,
'can_export' => true,
'rewrite' => true,
'capability_type' => 'post'
);
This code above may look like a lot and almost seem like an unknown language to you if
youre new to WordPress but if not youll recognize this code as a Custom Post Type. In this
case our custom post type is called music_review. The code is essentially telling WordPress
to establish a new type of post within your theme. The post type has parameters that go
along with it such as labels, arguments, and more. I wont go into a ton of detail on how
Custom Post Types work because Ive already covered it within another article on Elegant
Themes. Be sure to read it to gain a full understanding.
With our post type set up you can already see it active within the WordPress admin area.
Our custom post type is successfully implemented.
Lets take things one set further and include a custom Taxonomy called Genre inside our
plugin. Think of a Taxonomy as a type of categorizing feature that is completely custom.
WordPress already includes Categories and Tag support by default but developers can
create custom taxonomies to extend their themes or plugins even further.
Read more about WordPress Taxonomies here.
Add the code below under the custom post type function we just added.
function genres_taxonomy() {
register_taxonomy(
'genres',
'music_review',
array(
'hierarchical' => true,
'label' => 'Genres',
'query_var' => true,
'rewrite' => array(
'slug' => 'genre',
'with_front' => false
)
)
);
}
add_action( 'init', 'genres_taxonomy');
Registering a new Taxonomy is relatively easy. We have made the connection to our custom
post type by using the
register_taxonomy() function which creates a new taxonomy called genres and assigns
it to our post type music_review.
We need to add one more line to our custom post type to make everything sync up. Add this
code just below the supports argument within the custom post type.
Heres all our plugin code up until this point. For better legibility Ive stripped our code of any
comments we had prior to this.
function register_cpt_music_review() {
$labels = array(
'name' => _x( 'Music Reviews', 'music_review' ),
'singular_name' => _x( 'Music Review', 'music_review' ),
'add_new' => _x( 'Add New', 'music_review' ),
'add_new_item' => _x( 'Add New Music Review', 'music_review'),
'edit_item' => _x( 'Edit Music Review', 'music_review' ),
'new_item' => _x( 'New Music Review', 'music_review' ),
'view_item' => _x( 'View Music Review', 'music_review' ),
'search_items' => _x( 'Search Music Reviews', 'music_review'),
'not_found' => _x( 'No music reviews found', 'music_review'),
'not_found_in_trash' => _x( 'No music reviews found in
Trash', 'music_review' ),
'parent_item_colon' => _x( 'Parent Music Review:','music_review' ),
'menu_name' => _x( 'Music Reviews', 'music_review' ),
);
$args = array(
'labels' => $labels,
'hierarchical' => true,
'description' => 'Music reviews filterable by genre',
'supports' => array( 'title', 'editor', 'author','thumbnail', 'trackbacks'
, 'custom-fields', 'comments', 'revisions','page-attributes' ),
'taxonomies' => array( 'genres' ),
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 5,
'menu_icon' => 'dashicons-format-audio',
'show_in_nav_menus' => true,
'publicly_queryable' => true,
'exclude_from_search' => false,
'has_archive' => true,
'query_var' => true,
'can_export' => true,
'rewrite' => true,
'capability_type' => 'post'
);
function genres_taxonomy() {
register_taxonomy(
'genres',
'music_review',
array(
'hierarchical' => true,
'label' => 'Genres',
'query_var' => true,
'rewrite' => array(
'slug' => 'genre',
'with_front' => false
)
)
);
}
add_action( 'init', 'genres_taxonomy');
The only line that changed was the 'taxonomies' => array('genre') line within our
custom post type. I added this line to tell our custom post type to connect to our new
taxonomy and use it instead of the default category or tag structure WordPress comes
installed with.
If youve made it this far you can now visit your WordPress admin area and see your new
custom post type and taxonomy(Genres) present. Congrats!
Our custom post type and taxonomy are successfully implemented. Here we can add a new Music Review
which contains various types of genres decided upon by the user.
'closed' ,
And finally we need to create our Music Reviews page once the plugin is activated. Adding
the code below initiates the function we just wrote above ( function
create_music_review_pages(){}).
// // Activates function if plugin is activated
register_activation_hook( __FILE__, 'create_music_review_pages');
Testing
Our plugin should be ready to test at this point. Lets create an example music review and see
what outputs.
If you click View Music Review once the post is published you should be taken to a screen
which looks similar to the image below. Your theme and styles may vary
You may notice that I modified the menu to include our new Music Reviews page. Doing this
gives us easy access.
With your menu in place and saved click on Music Reviews to see all the posts we have
made so far.
Based on the page template supplied by your theme the Music Review should output all
together and be clickable through to the single review template. You will probably notice that
the music review I posted earlier has output as well as the one we just created.
Our feature image, title, genre, and review all have posted successfully. Our plugin works!
To verify, you can deactivate the plugin and reinstall it or activate it. Upon doing so a new
Page called Music Reviews should be created. You can delete or reuse the one from before
if there are duplicates but there should be only one Music Reviews page. We could have
added a function to delete and restore this page within our plugin but I wanted to keep things
as simple as possible.
Finish
Our plugin is a relatively simple one. You can extend it so much further by including its own
predefined templates, custom widgets, more taxonomies and so much more. Creating a
plugin is no easy feat. You will want to plan your plugin before even moving to development.
Knowing what you can an cant do with WordPress before coding your own plugin is a crucial
step to developing a quality one. The plugin create in this tutorial is meant to teach by
example. There are better standards to follow and more useful practices to endure. Be sure
to read the WordPress Codex and get familiar with the WordPress Plugin API. If a plugin isnt
out there and you need custom functionality for your website then I stronger encourage trying
to create your own!
Plugin API
Languages: English Espaol Franais Portugus do Brasil () (Add your
language)
Contents
1 Introduction
3 Function Reference
4 Actions
5 Filters
5.5 Example
7 Pluggable Functions
8 Activation/Deactivation/Uninstall
9 Related
10 External Resources
Introduction
This page documents the API (Application Programming Interface) hooks available to WordPress plugin
developers, and how to use them.
This article assumes you have already read Writing a Plugin, which gives an overview (and many details) of
how to develop a plugin. This article is specifically about the API of "Hooks", also known as "Filters" and
"Actions", that WordPress uses to set your plugin in motion.
These hooks may also be used in themes, as described here.
Function Reference
Filter Functions
has_filter()
add_filter()
apply_filters()
apply_filters_ref_array()
current_filter()
remove_filter()
remove_all_filters()
doing_filter()
Actions Functions
has_action()
add_action()
do_action()
do_action_ref_array()
did_action()
remove_action()
remove_all_actions()
doing_action()
Activation/Deactivation/Uninstall Functions
register_activation_hook()
register_uninstall_hook()
register_deactivation_hook()
Actions
Actions are triggered by specific events that take place in WordPress, such as publishing a post, changing
themes, or displaying anadministration screen. An Action is a custom PHP function defined in your plugin (or
theme) and hooked, i.e. set to respond, to some of these events. Actions usually do one or more of the
following:
Modify the generated administration screen or front-end page sent to a user browser.
The basic steps to make this happen (described in more detail below) are:
1. Create a PHP function that should execute when a specific WordPress event occurs, in your plugin file.
2. Hook this function to the event by using the add_action() function.
3. Put your PHP function in a plugin file, and activate it.
The first step in creating an action in your plugin is to create a PHP function with the action functionality of your
plugin, and put it in your plugin file (your plugin file must go into the wp-content/plugins directory). For example,
if you want your friends to get an email message whenever you create a new post, you might define the
following function:
function email_friends($post_ID)
$friends = 'bob@example.org,susie@example.org';
return $post_ID;
For most actions, your function should accept a single parameter (usually the post or comment ID, depending
on the action). Some actions take more than one parameter -- check the documentation for the action (if
available) or the WordPress source code for more information. Besides the one parameter, you can also access
the global variables of WordPress, and call other WordPress functions (or functions in your plugin file).
Any text output by the function (e.g. with print) will appear in the page source at the location where the action
was invoked.
NOTE: Keep in mind that other plugins or the WordPress core may already be using the function name you
have thought of. See the next section, Avoiding Function Name Collisions for more information.
class emailer {
$friends = 'bob@example.org,susie@example.org';
return $post_ID;
This class, called emailer has a method send that implements the plugin functionality.
The add_action() function outside of the class adds the action to WordPress that tells it to call the send method
when a post is published. The array used in the second parameter tells the plugin system to call the static
method of the class 'emailer' named 'send'.
The function send is protected from the global namespace by the class declaration. It is not possible to call
send() directly, and so any other function named send will not collide with this one. If you did want to call send(),
you would need to use a scope resolution operator, like this: emailer::send()
The above example is for static methods. If you have an instance of a class then that won't work. To call a
method of an instance you need to pass the instance as a variable. Consider the above example modified to
take this into account:
class emailer {
function send($post_ID)
$friends = 'bob@example.org,susie@example.org';
return $post_ID;
Classes are a complicated subject. Read more about them in the PHP documentation on classes.
Hook to WordPress
After your function is defined, the next step is to "hook" or register it with WordPress. To do this,
call add_action() in the global execution space of your plugin file:
where:
hook_name
The name of an action hook provided by WordPress, that tells what event your function should be
associated with.
your_function_name
The name of the function that you want to be executed following the event specified by hook_name.
This can be a standard php function, a function present in the WordPress core, or a function defined by
you in the plugin file (such as 'email_friends'defined above).
priority
An optional integer argument used to specify the order in which the functions associated with a
particular action are executed (default: 10). Lower numbers correspond with earlier execution, and
functions with the same priority are executed in the order added to the action.
accepted_args
An optional integer argument defining how many arguments your function can accept (default 1), useful
because some hooks can pass more than one argument to your function. This parameter is new in
release 1.5.1.
Return Value
The (optionally modified) value of the first argument passed to the filter function.
In the example above, we would put the following line in the plugin file:
Likewise, you can also Remove Actions from action hooks. See that section for details.
the wp-content/plugins directory. Once it is installed, you will need to visit the admin section of WordPress and
activate your plugin; see Managing Plugins for more details.
Filters
Filters are functions that WordPress passes data through, at certain points in execution, just before taking
some action with the data (such as adding it to the database or sending it to the browser screen). Filters sit
between the database and the browser (when WordPress is generating pages), and between the browser and
the database (when WordPress is adding new posts and comments to the database); most input and output in
WordPress passes through at least one filter. WordPress does some filtering by default, and your plugin can
add its own filtering.
The basic steps to adding your own filters to WordPress (described in more detail below) are:
1. Create the PHP function that filters the data.
2. Hook to the filter in WordPress, by calling add_filter().
3. Put your PHP function in a plugin file, and activate it.
$profanities = array('badword','alsobad','...');
return $content;
Why does this work without a loop? Because $profanities is an array, and str_ireplace loops through the array
for you. Thestr_ireplace function is used instead of str_replace because str_ireplace is case insensitive.
NOTE: Keep in mind that other plugins or the WordPress core may already be using the function name you
have thought of. See thePlugin Development Suggestions for more information.
where:
hook_name
The name of a filter hook provided by WordPress, which defines when your filter should be applied.
your_filter
The name of the function that you want to use for filtering. This can be a standard PHP function, a
function present in the WordPress core, or a function defined by you in the plugin file.
priority
An optional integer argument that can be used to specify the order in which the functions associated
with a particular filter are executed (default: 10). Lower numbers correspond with earlier execution, and
functions with the same priority are executed in the order in which they were added to the filter.
accepted_args
An optional integer argument defining how many arguments your function can accept (default 1), useful
because some hooks can pass more than one argument to your function.
In the example above, we would put the following in the main executing section of the plugin file, to tell
WordPress to filter comments for profanity:
You can also remove filters from filter hooks using the remove_filter() function. See Removing Actions and
Filters.
Example
This is an example, as described by Ozh on the wp-hackers email list, for a plugin to modify (or overwrite) the
default bloginfo()function. This will require modifying a core function behavior.
add_filter( 'bloginfo', 'mybloginfo', 1, 2 );
switch ( $show ) {
case 'wpurl':
$result = SITE_URL;
break;
case 'template_directory':
$result = TEMPL_DIR;
break;
default:
return $result;
Note that if a hook was registered using a priority other than the default of 10, then you must also specify the
priority in the call toremove_action(). Also note that in general, you shouldn't remove anything unless you
know what it does and why it does it -- check the WordPress or other plugin source code to be sure.
Pluggable Functions
Besides the hooks (actions and filters) described above, another way for a plugin to modify WordPress's
behavior is to override WordPress functions. In fact, there is a small set of functions WordPress intends for
plugins to redefine. These are called Pluggable Functions and they are defined in wp-includes/pluggable.php.
WordPress loads these functions only if they are still undefined after all plugins have been loaded. For more
details examine wp-settings.php file.
Activation/Deactivation/Uninstall
If your plugin has tasks to complete only at activation or deactivation time, it can
use register_activation_hook andregister_deactivation_hook. Many plugins do not need to use
these, as the plugins only modify current behavior. However, if your plugin (for example) needs to change a
default option on activation, it can use these functions.
Creating Tables with Plugins has an example using the register_activation_hook function to make the
database compatible with the current version of the plugin.
The register_uninstall_hook gives your plugin the option of cleaning up after itself when it is deleted
from the WordPress installation. Users have reasons to temporarily deactivate plugins, so do not do anything
from the deactivation hook that would lose any user settings. This is what the uninstall hook is for.