I have been trying to learn how to write plugins and I thought the best way would be to look at other plugins.
I was taking a look at this one and the first lines
/**
* Plugin Name: Media Library Categories
* Plugin URI: http://wordpress.org/plugins/wp-media-library-categories/
* Description: Adds the ability to use categories in the media library.
* Version: 1.4.1
* Author: Jeffrey-WP
* Author URI: http://codecanyon.net/user/jeffrey-wp/?ref=jeffrey-wp
*/
/** register taxonomy for attachments */
function wpmediacategory_init() {
// Default taxonomy
$taxonomy = 'category';
// Add filter to change the default taxonomy
$taxonomy = apply_filters( 'wpmediacategory_taxonomy', $taxonomy );
register_taxonomy_for_object_type( $taxonomy, 'attachment' );
}
add_action( 'init', 'wpmediacategory_init' );
There is this line:
$taxonomy = apply_filters( 'wpmediacategory_taxonomy', $taxonomy
that I don’t understand. I have look around the WordPress documentation and I didnt find a hook called wpmediacategory_taxonomy
. Besides due to the name, I am sure that is something related to the plugin. So how does it exactly work? Is that a custom hook? Where was it defined?
Hook use is very, very simple. To create a hook use
apply_filters
ordo_action
.The first parameter is the hook name, the other parameters are the arguments.
You must have the hook name, but the other arguments are optional. You can have, so far as I know, as many arguments as you like. For example:
That act of “applying” the filter is what “triggers” it. This line is where the filter runs. And you can run a set of filters multiple times, not just once.
To add a filter, you create a callback (closures are fine) and add it to the hook. For example:
The fourth argument in the count of arguments you need. Without it, you only get the first argument passed through to your callback.
Actions do not return data, though you can
echo
it.Filters should return data, though don’t have to, but know what your are doing if you don’t. Specifically, you should return the data from the first parameter and in the same format– that is, if you get a string, return a string. You should not
echo
data from a filter as that usually causes very strange effects.You almost gave the answer yourself.
apply_filters, as the name says applies all filters registered for this filter hook. This can be a default WordPress filter but also like in this case a custom one from a plugin.
This only invokes any registered callbacks. Adding filters is done with add_filter()
More information can be found in the Codex: apply filters