Using WordPress ‘do_action()’ PHP function

The do_action() WordPress PHP function is used to call the callback functions that have been added to an action hook.

Usage

To use do_action(), you create a new action hook and specify the name of the new hook using the $hook_name parameter. You can also pass extra arguments to the hooks. Below is a generic usage example:

// The action callback function.
function example_callback( $arg1, $arg2 ) { 
    // (maybe) do something with the args.
}

add_action( 'example_action', 'example_callback', 10, 2 );

// Trigger the actions by calling the 'example_callback()' function
// that's hooked onto `example_action` above.
do_action( 'example_action', $arg1, $arg2 );

Parameters

  • $hook_name (string, required) – The name of the action to be executed.
  • $arg (mixed, optional) – Additional arguments which are passed on to the functions hooked to the action. Default is empty.

More information

See WordPress Developer Resources: do_action()
Related functions include add_action() and remove_action().

Examples

Display Data

In this example, we’ll hook a function that displays some data when the action is called.

function display_data( $text ) {
    echo $text;
}

add_action( 'show_text', 'display_data', 10, 1 );

do_action( 'show_text', 'Hello, World!' ); // Outputs: Hello, World!

User Registration

In this scenario, we’ll use do_action() to hook into the user registration process.

function new_user_registered( $user_id ) {
    // Send notification, log activity, etc.
}

add_action( 'user_register', 'new_user_registered', 10, 1 );

// This is typically called when a new user is registered.
do_action( 'user_register', $new_user_id );

Modify Post Content

This example shows how to use do_action() to modify post content.

function modify_content( $content ) {
    return $content . ' Thank you for reading!';
}

add_action( 'the_content', 'modify_content' );

// This is usually hooked into WordPress' loop.
do_action( 'the_content', $post->post_content );

Custom Action Hook

You can create a custom action hook. Suppose we want to create a custom hook called ‘my_custom_hook’ and work with it.

do_action( 'my_custom_hook' );

function wporg_my_custom_hook_function() {
    echo "This is a custom hook!";
}

add_action( 'my_custom_hook', 'wporg_my_custom_hook_function' );

Warning about Arrays

When calling do_action(), if the $arg you pass in is an array with a single object, it will instead pass that object in and NOT an array.

function my_callback( $should_be_an_array ){
    var_dump($should_be_an_array);
}

add_action( 'my_action', 'my_callback' );

do_action( 'my_action', array(new stdclass()) ); 
do_action( 'my_action', array( 'array_item_thats_not_an_object') ); 

Notice that the first time we passed in an array with an stdClass in it, but the callback function only received the stdClass, NOT an array.