What are WordPress actions and how to use WordPress add_action() function

WordPress is a highly customizable platform that allows users to extend its functionality through various hooks and functions. One of the most used functions is add_action(), which lets you add custom behavior to your site without modifying WordPress core files.

In this article, you’ll learn how to use WordPress’s add_action() function to connect your custom code with predefined actions within the platform. By mastering this function, you can easily enhance your website’s capabilities and tailor it to your needs.

Download all in one WordPress cheat sheet

WordPress actions are hooks that execute custom code at specific points during the WordPress execution process. These action hooks trigger functions when certain events occur, like loading the header or publishing a post.

WordPress hooks are divided into two types—actions and filters. While actions let you add or modify functionality by attaching functions to specific events, filters alter data as WordPress processes it.

For example, the add_action() function adds your custom code to run when a post is published, while add_filter() modifies a post’s content before displaying it.

How do WordPress actions work?

WordPress actions work by inserting custom functions into predefined events in the WordPress lifecycle. The add_action() function hooks these events so that your custom code runs at the appropriate time.

For instance, if you want to add a custom script to your site’s header, you can use the wp_head action hook. WordPress will execute your code whenever it reaches your site’s header while the page loads by hooking your function to this event.

Adding actions to WordPress

You can add actions to WordPress in several ways, depending on where you want to place your custom code:

  • Theme’s functions.php file. This is the most common place to add actions if your custom functionality is tied to the theme. Open your active theme’s functions.php file and add your add_action() code.
  • Child theme’s functions.php file. If you’ve created a child theme, you can place your actions in the child theme’s functions.php file. This method is helpful if you want to keep your changes separate from the parent theme.
  • Custom plugin. Consider creating a custom plugin if you want your custom actions independent of the theme. This way, your code will continue to work even if you change your site’s theme. To do this, create a new PHP file in the wp-content/plugins/ directory, add your add_action() code, and activate the plugin.

WordPress add_action() parameters

The WordPress add_action() function controls how and when your custom code is executed by taking several parameters. Let’s break them down:

  • $hook_name. This parameter specifies the action hook name to which you want to attach your custom function. This hook determines when your function will run. WordPress has many predefined hooks, such as init to run code after WordPress has finished loading and wp_footer to add code to the footer.
  • $callback. Often referred to as the callback function, it’s the function name you wish to execute when the specified action hook is triggered. This function contains the custom code that will run at the appropriate point in WordPress.
  • $priority (optional). The $priority parameter determines the order in which WordPress executes functions tied to the same hook. The default priority is 10, but you can adjust this value to control whether your function runs earlier or later than other functions in the same action. Lower numbers mean the function will run sooner.
  • $accepted_args (optional). It defines the number of arguments that your callback function can accept. By default, WordPress sets this to 1, but you can increase it if your function needs to accept more arguments.

Here’s an example of a complete add_action() function:

function my_custom_script() {

echo '<script>alert("Hello, World!");</script>';

}

add_action( 'wp_footer', 'my_custom_script', 10, 1 );
  • $hook_name – ‘wp_footer’. This specifies that the function should run when the wp_footer action hook is triggered, which happens when WordPress is about to close the body tag on every page.
  • $callback – ‘my_custom_script’. The function name that will be executed when the wp_footer hook is called.
  • $priority – 10. This is the default priority, meaning the function will run in the standard order relative to other functions hooked to wp_footer.
  • $accepted_args – 1. Although this function doesn’t require arguments, WordPress sets it to accept 1 argument by default.

As the WordPress page loads the footer, the my_custom_script function executes, inserting a script that displays an alert box with the message “Hello, World!” before the page closes.

Example of add_action() in WordPress

This section demonstrates some practical uses of the add_action() function. If you host your WordPress site on Hostinger and want to try these examples, test them in a staging environment first.

This way, you can safely experiment without affecting your live site. You can follow our guide on setting up a WordPress staging environment using Hostinger’s staging tool.

Adding a custom script to the WordPress frontend

One common use of add_action() is inserting custom scripts into your WordPress site’s frontend. This can be useful when you need to include JavaScript files or inline scripts that enhance your site’s functionality or design.

For instance, add a custom JavaScript file to your site’s header to create interactive elements or track user behavior. To achieve this, hook into the wp_enqueue_scripts action, which enqueues scripts and styles in WordPress.

Here’s how to do it:

function add_custom_script() {

wp_enqueue_script( 'custom-js', get_template_directory_uri() . '/js/custom-script.js', array(), null, true );

}

add_action( 'wp_enqueue_scripts', 'add_custom_script' );

In this example, you call the wp_enqueue_script function with several parameters:

  • ‘custom-js’ – a unique handle for your script.
  • get_template_directory_uri() . ‘/js/custom-script.js’ – your JavaScript file’s location within your theme directory.
  • array() – an array of dependencies for your script. You can leave this empty if there are none.
  • null (optional) – the script version number.
  • true – whether to load the script in the footer (true) or the header (false).

The add_action(‘wp_enqueue_scripts’, ‘add_custom_script’) line hooks your add_custom_script function to the wp_enqueue_scripts action. This approach prevents conflicts with other themes or plugins that might be enqueuing their scripts.

You can also use the add_action() function to customize your WordPress site’s footer. Whether you want to display a personalized message, add a copyright notice, or include extra HTML or scripts, the wp_footer hook provides the ideal opportunity.

This hook is triggered just before the closing </body> tag on every page of your WordPress site. It’s the perfect place to add custom content that you want to appear site-wide, as shown in the following example:

function add_custom_footer_message() {

echo '<p style="text-align: center;">Thank you for visiting our website!</p>';

}

add_action( 'wp_footer', 'add_custom_footer_message' );

Here, you add a simple HTML paragraph with a centered text message. Then, add_action() hooks the add_custom_footer_message function to the wp_footer action.

As a result, every time WordPress reaches the wp_footer hook, the custom message is displayed in the site’s footer.

Adding a custom admin notice

In WordPress, admin notices effectively communicate important information to users within the admin dashboard. These notices can display warnings, updates, or other messages that need the site administrator’s attention.

Hooking add_action() into the admin_notices action triggers the notice at a specific point whenever the WordPress admin area loads. The following code snippet shows how to add a custom admin notice:

function custom_admin_notice() {

echo '<div class="notice notice-success is-dismissible">

<p>This is a custom admin notice!</p>

</div>';

}

add_action( 'admin_notices', 'custom_admin_notice' );

This custom WordPress function generates the HTML for the admin notice. The <div> element includes several classes:

  • notice – this class is required to style the element as an admin notice.
  • notice-success – it defines the notice as a success message. To display different types of messages, change this to notice-warning, notice-error, or notice-info.
  • is-dismissible – this class adds a close button so users can dismiss the notice.

You can add logic to your custom function to display the notice only under certain conditions, such as when editing a specific post type or after updating a plugin.

Here’s an example that shows an admin notice only when you edit a certain post type:

function conditional_admin_notice() {

global $post;

if ( $post->post_type == 'your_post_type' ) {

echo '<div class="notice notice-warning is-dismissible">

<p>This is a custom notice for your post type.</p>

</div>';

}

}

add_action( 'admin_notices', 'conditional_admin_notice' );

Adding a custom sidebar widget

A widget is a small block that performs a specific function, such as displaying recent posts, a search bar, or custom HTML. Using the widgets_init action hook, you can register and display your custom widget in your sidebar or any other widget area.

First, define a custom class that extends WP_Widget to add a custom sidebar widget. This class will contain your custom widget’s logic, including how it’s displayed and any form fields for customizing its content.

class My_Custom_Widget extends WP_Widget {

// Constructor to set up the widget's name, description, etc.

public function __construct() {

parent::__construct(

'my_custom_widget', // Base ID

__( 'My Custom Widget', 'text_domain' ), // Widget name in the admin

array( 'description' => __( 'A custom widget that displays a message.', 'text_domain' ), ) // Widget description

);

}

// Output the content of the widget on the frontend

public function widget( $args, $instance ) {

echo $args['before_widget'];

echo $args['before_title'] . apply_filters( 'widget_title', $instance['title'] ) . $args['after_title'];

echo '<p>' . __( 'Hello, this is my custom widget!', 'text_domain' ) . '</p>';

echo $args['after_widget'];

}

// Output the widget options form on the admin

public function form( $instance ) {

$title = ! empty( $instance['title'] ) ? $instance['title'] : __( 'New title', 'text_domain' );

?>

<p>

<label for="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>"><?php _e( 'Title:', 'text_domain' ); ?></label>

<input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'title' ) ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>">

</p>

<?php 

}

// Process widget options to save

public function update( $new_instance, $old_instance ) {

$instance = array();

$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? sanitize_text_field( $new_instance['title'] ) : '';

return $instance;

}

}

In the above snippet, My_Custom_Widget extends the WP_Widget class and includes methods for displaying the widget (widget), generating the widget’s admin form (form), and saving the widget’s options (update).

After defining the custom class, register it using the widgets_init action hook. This is where add_action() comes into play:

function register_my_custom_widget() {

register_widget( 'My_Custom_Widget' );

}

add_action( 'widgets_init', 'register_my_custom_widget' );

By hooking your register_my_custom_widget function to widgets_init, WordPress will register your custom widget when it prepares the widget system. You can then add it to the sidebar or other widgetized area.

Other WordPress action functions

In addition to add_action(), several other functions in WordPress interact with action hooks. These functions enable you to execute custom code, remove actions, and check if specific actions have been registered.

do_action()

The do_action() function triggers an action hook. It lets you execute all the functions hooked to a particular action. You can use it within your custom code to create a new action that you or other developers can hook into, allowing for extensibility and modular code.

do_action( 'my_custom_action' );

In this example, the do_action() function triggers the my_custom_action hook.

remove_action()

In contrast, remove_action() unhooks a function from a specific action hook. This can be helpful when you need to override or stop a particular function from running, especially when dealing with third-party plugins or themes.

remove_action( 'wp_head', 'wp_generator' );

Here, you use remove_action() to unhook wp_generator from wp_head.

has_action()

Use the has_action() function to verify if an action hook has any functions attached to it before executing certain code, ensuring that the action you intend to modify is indeed hooked.

if ( has_action( 'wp_footer', 'my_custom_footer' ) ) {

// The custom footer function is hooked, so do something

In the above example, has_action() checks whether the my_custom_footer function is hooked to the wp_footer action. If it is, you can use a conditional statement to execute additional logic based on that condition.

Conclusion

This article covered how the WordPress add_action() function enables you to extend and customize your website. From adding custom scripts and footer messages to creating unique sidebar widgets, you can quickly tailor your site’s functionality without altering core files.

We’ve also discussed other action-related functions like do_action(), remove_action(), and has_action(), giving you even more control over how and when WordPress executes your custom code. Mastering these tools lets you create a more dynamic and personalized WordPress website.

WordPress add_action() FAQ

What is the difference between add_action() and add_filter()?

add_action() inserts custom functions into action hooks that execute at specific points, while add_filter() attaches functions to filter hooks that modify data before it is displayed. Both are important for extending WordPress functionality.

Is it safe to use add_action() in the functions.php file?

Yes, it’s safe to use add_action() in the functions.php file. However, consider creating a custom plugin for complex or reusable code to keep your WordPress code clean and maintainable.

What is the difference between do_action() and add_action()?

add_action() registers a function to run when an action hook is triggered, while do_action() triggers that hook, executing all attached functions. Together, they allow for flexible and modular code execution in WordPress.

Author
The author

Ariffud Muhammad

Ariffud is a Technical Content Writer with an educational background in Informatics. He has extensive expertise in Linux and VPS, authoring over 200 articles on server management and web development. Follow him on LinkedIn.