In a previous section, we explore how plugins interact with WordPress by using the plugin API. Here, we show you how functions are defined in a plugin. In PHP, a function is a predefined set of commands carried out when the function is called. It's the same in WordPress; some functions are common PHP functions, and some functions are specific to WordPress. We discuss how to hook into these functions through the plugin API so that you can call existing commands instead of having to write them over again in your plugin. However, you can also write your own functions and call them in your plugin.
So how do you identify functions within a plugin? Here's an example from the Hello Dolly plugin; this code function is found at the bottom, as the last line of the plugin file: hello.php:
add_action('admin_head', 'dolly_css'),
The WordPress Codex documentation describes the add_action function as having the following arguments, or parameters:
add_action( $tag, $function_to_add, $priority, $accepted_args );
In PHP code, the dollar sign, $, simply tells PHP that the word appearing directly after it is a variable that is defined. In our example, $tag is a variable that is defined in the add_action function.
The code in our example uses add_action to hook the dolly_css function to the admin_head action. Therefore, the dolly_css function must be defined somewhere in the plugin and must look like this:
function dolly_css() { }
Between the {} brackets is the set of commands that carry out when the function is called. This function is called when WordPress runs admin_head. You see the set of commands for the dolly_css function earlier in this chapter, in the “Understanding action hooks” section.
This simple example outputs Hello in the head of the Web site:
add_action('wp_head;, 'my_function'), function my_function() { echo "Hello"; }
Both add_action and add_filter contain a $tag, which is the name of the hook in the plugin API, and a $function, which is then defined in the plugin using function function_name() { }.