Here is how my current action hook example: it changes the meta description of the HTML page.
add_action( 'wp_head', 'add_a_description' );
function add_a_description () {
echo '<meta name="description" content=" This is new content" />' . "
";
} // End example
Now to me (I have some basic PHP knowledge, nothing more), it looks like the function is being called before it’s been made. My intuition tells me that it should look like:
function add_a_description () {
echo '<meta name="description" content=" This is new content" />' . "
";}
add_action( 'wp_head', 'add_a_description' ); // End example
I understand this isn’t the case, but I don’t know why. Could someone explain it to me?
It does not matter where you write the action hook both will work:
and
These both will work. It does not matter where you declare the function, the only thing is that the function should be included in the script.
This is because the
whole file is first parsed and then executed
.From PHP Manual
Functions need not be defined before they are referenced, except when a function is conditionally defined.
Regarding the
wp_head
action hook. Thewp_head
function resides insidewp-includes/general-template.php
If you look at that function it will call
do_action('wp_head');
What this does is that, it will check for all actions and filters defined with wp_head hook which is stored in the global variable $wp_actions
If there is a hook in for wp_head it will call the hooked function using call_user_func_array
Hope this helps you 🙂
Without knowing all of the inner workings, you can think of
add_action()
as simple function which passes the name of a function to be called at a certain point. In your code,add_action()
lets the system know to call the functionadd_a_description()
when it reaches thewp_head
point.Here’s a VERY basic example of how the code works: