Identifying Functions within a Plugin

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 );
  • $tag is the name of the action you want to hook onto.
  • $function_to_add is the name of the function you're calling.
  • $priority is an optional value that represents how important the function is. The default is 10, a lower number makes the function run earlier, and a higher number makes the function run later.
  • $accepted_args is the number of arguments your function takes. This is optional, and the default is 1.

image 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() { }.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.213.238