How to Trigger an Action in WordPress

The function do_action triggers an action in WordPress.

Background

WordPress actions allow the injection of code into a subject to perform custom tasks. An action consists of a name and a set of callbacks. When an action is triggered, WordPress executes all callbacks hooked to the action. The execution is sequential according to the priority of each callback.

Syntax

do_action($tag, $arg1, $arg2, …) executes all callbacks hooked to the $tag action. Arguments after $tag are optional and you can pass as many as needed. If they are specified, WordPress passes them to each callback hooked to the action.

WordPress also has the function do_action_ref_array($tag, $args) to trigger actions. The difference is that in this case optional arguments are supplied as elements of the $args array.

A call to do_action or do_action_ref_array creates an extension point. Anyone can hook functions to the action to inject custom code at the specific point where the action is triggered.

Examples

The WordPress Core triggers actions in many places. To check it, open the search feature of the IDE and find occurrences of do_action or do_action_ref_array in the codebase.

For example, the 'trashed_post' action is triggered in the file post.php to notify that a post has been sent to the Trash

/**
 * Fires after a post is sent to the trash.
 *
 * @since 2.9.0
 *
 * @param int $post_id Post ID.
 */
do_action( 'trashed_post', $post_id );

and the 'delete_attachment' action is triggered in the file post.php to notify that an attachment is being deleted.

/**
 * Fires before an attachment is deleted, at the start of wp_delete_attachment().
 *
 * @since 2.0.0
 *
 * @param int $post_id Attachment ID.
 */
do_action( 'delete_attachment', $post_id );

Further reading

I recommend the other tutorials in this series to learn more about actions in WordPress.

Exercise

Suppose a solution where posts can be locked or unlocked. Develop a function that changes the lock status of a post. The function should allow plugins and themes to execute custom code after the lock status of a post is changed.

Source code

The source code developed in this tutorial, including a possible answer to the exercise, is available here.