Understanding how WordPress hooks are called

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:

Read More
      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?

Related posts

Leave a Reply

2 comments

  1. It does not matter where you write the action hook both will work:

    add_action( 'wp_head', 'add_a_description' );
    
    function add_a_description () {
        echo '<meta name="description" content=" This is new content" />' . "";
    } 
    

    and

    function add_a_description () {
        echo '<meta name="description" content=" This is new content" />' . "";
    } 
    
    add_action( 'wp_head', 'add_a_description' );  // End example
    

    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. The wp_head function resides inside wp-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 🙂

  2. 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 function add_a_description() when it reaches the wp_head point.

    Here’s a VERY basic example of how the code works:

    // Start of example system
    $actions = array();
    
    function add_action($point, $name) {
      global $actions;
      $actions[$point][] = $name;
    }
    
    function run($point) {
      global $actions;
      foreach ($actions[$point] as $name)
        $name();
    }
    // End of example system
    
    // Start of example plugin / theme function
    add_action('wp_head', 'alert');
    function alert() {
      echo 'hello';
    }
    // End of example plugin / theme function
    
    // At point wp_head
    run('wp_head');