Dev Notes

Software Development Resources by David Egan.

WordPress Action Hooks


WordPress
David Egan

Placing do_action( $tag, $arg ) within a theme or plugin allows all functions attached to the action hook $tag to be invoked at this specific point.

A callback function is registered to the action hook by means of the add_action() function, using the $tag defined in do_action().

This enables you to create an API for a theme or plugin - callbacks can be registered for a custom action.

To register a callback, use add_action(). This will typically be in the theme custom functions, where the related $function_to_add will also be defined:

<?php
add_action( $hook, $function_to_add, $priority, $accepted_args );

To execute the callback, use do_action(). This will typically be in the template or layout partial - anywhere where you’d like to give developers (or yourself) the ability to hook in additional content:

<?php
do_action( $tag, $arg_a, $arg_b, $etc );

Simplest Example

Simple example of an action hook - allows extra content to be added by the theme.

Register hook before address - added in theme template or plugin layout:

<?php
do_action( 'before_address' );
echo carawebs_custom_address();

// This could also be defined as part of a function or class method like this:
function carawebs_before_address() {

    do_action( 'before_address' );

}
// The function call `carawebs_before_address()` would then be added to the template.

We can now add HTML before the address block, by hooking to the ‘before_address’ action hook. This gives layout control to the theme, which is proper.

The following code would typically be located in the theme custom functions.

namespace Carawebs\Namespace;

function address_title() {

  echo "<h2>A Custom Title</h2>";

}

add_action (  'before_address', 'Carawebs\Namespace\address_title', 1 );

Arguments for the Action Hook Callback

The callback function that is registered by means of add_action() can accept arguments. The number of arguments must agree with those defined in the corresponding do_action().

This means that variables defined in the same scope as the do_action() call can be made available to the callback registered in add_action().

Within the template (or better within a function invoked from the template):

$i = 1;

foreach( $people as $person ){

  // Pass $i as an argument to do_action
  echo do_action( 'carawebs_before_person', $i );
  echo $person['name'] . "<br />";
  echo $person['title'] . "<br />";
  echo "<hr>";

  $i++;

}

Within the theme custom functions:

// $i is passed into the function by the do_action() setup.
function carawebs_person_intro( $i ) {

  // Echoes a numbered intro
  echo "This is data for person $i";

}

// add_action( $tag, $callback, $priority, $accepted_arguments )
add_action( 'carawebs_before_person', 'carawebs_person_intro', 1, 1 );

Resources


comments powered by Disqus