Adds a callback function to an action hook.
Description
Actions are the hooks that the WordPress core launches at specific points during execution, or when specific events occur. Plugins can specify that one or more of its PHP functions are executed at these points, using the Action API.
Parameters
$hook_name
stringrequired- The name of the action to add the callback to.
$callback
callablerequired- The callback to be run when the action is called.
$priority
intoptional- Used to specify the order in which the functions associated with a particular action are executed.
Lower numbers correspond with earlier execution, and functions with the same priority are executed in the order in which they were added to the action.Default:
10
$accepted_args
intoptional- The number of arguments the function accepts.
Default:
1
Return
true Always returns true.More Information
Usage
add_action( $hook, $function_to_add, $priority, $accepted_args );
To find out the number and name of arguments for an action, simply search the code base for the matching do_action() call. For example, if you are hooking into ‘save_post’, you would find it in post.php:
do_action( 'save_post', $post_ID, $post, $update );
Your add_action call would look like:
add_action( 'save_post', 'wpdocs_my_save_post', 10, 3 );
And your function would be:
function wpdocs_my_save_post( $post_ID, $post, $update ) {
// do stuff here
}
Source
function add_action( $hook_name, $callback, $priority = 10, $accepted_args = 1 ) {
return add_filter( $hook_name, $callback, $priority, $accepted_args );
}
Related
Uses | Description |
---|---|
add_filter()wp-includes/plugin.php | Adds a callback function to a filter hook. |
Used by | Description |
---|---|
WP_Script_Modules::add_hooks()wp-includes/class-wp-script-modules.php | Adds the hooks to print the import map, enqueued script modules and script module preloads. |
WP_Textdomain_Registry::init()wp-includes/class-wp-textdomain-registry.php | Initializes the registry. |
wp_initialize_theme_preview_hooks()wp-includes/theme-previews.php | Add filters and actions to enable Block Theme Previews in the Site Editor. |
WP_Rewrite::refresh_rewrite_rules()wp-includes/class-wp-rewrite.php | Refreshes the rewrite rules, saving the fresh value to the database. |
wp_delete_all_temp_backups()wp-includes/update.php | Schedules the removal of all contents in the temporary backup directory. |
_wp_get_iframed_editor_assets()wp-includes/block-editor.php | Collect the block editor assets that need to be loaded into the editor’s iframe. |
wp_enqueue_block_support_styles()wp-includes/script-loader.php | Hooks inline styles in the proper place, depending on the active theme. |
_wp_theme_json_webfonts_handler()wp-includes/deprecated.php | Runs the theme.json webfonts handler. |
_add_template_loader_filters()wp-includes/block-template.php | Adds necessary hooks to resolve ‘_wp-find-template’ requests. |
wp_enqueue_block_style()wp-includes/script-loader.php | Enqueues a stylesheet for a specific block. |
locate_block_template()wp-includes/block-template.php | Finds a block template with equal or higher specificity than a given PHP template file. |
WP_Sitemaps::init()wp-includes/sitemaps/class-wp-sitemaps.php | Initiates all sitemap functionality. |
WP_Recovery_Mode::initialize()wp-includes/class-wp-recovery-mode.php | Initialize recovery mode for the current request. |
WP_Site_Health::__construct()wp-admin/includes/class-wp-site-health.php | WP_Site_Health constructor. |
wp_is_site_initialized()wp-includes/ms-site.php | Checks whether a site is initialized. |
register_and_do_post_meta_boxes()wp-admin/includes/meta-boxes.php | Registers the default post meta boxes, and runs the |
WP_Privacy_Policy_Content::text_change_check()wp-admin/includes/class-wp-privacy-policy-content.php | Performs a quick check to determine whether any privacy info has changed. |
WP_Roles::get_roles_data()wp-includes/class-wp-roles.php | Gets the available roles data. |
WP_Widget_Text::_register_one()wp-includes/widgets/class-wp-widget-text.php | Adds hooks for enqueueing assets when registering all widget instances of this widget class. |
WP_Widget_Custom_HTML::_register_one()wp-includes/widgets/class-wp-widget-custom-html.php | Add hooks for enqueueing assets when registering all widget instances of this widget class. |
WP_Widget_Media::_register_one()wp-includes/widgets/class-wp-widget-media.php | Add hooks while registering all widget instances of this widget class. |
_WP_Editors::enqueue_default_editor()wp-includes/class-wp-editor.php | Enqueue all editor scripts. |
_wp_delete_customize_changeset_dependent_auto_drafts()wp-includes/nav-menu.php | Deletes auto-draft posts associated with the supplied changeset. |
WP_Customize_Manager::import_theme_starter_content()wp-includes/class-wp-customize-manager.php | Imports theme starter content into the customized state. |
WP_Post_Type::register_meta_boxes()wp-includes/class-wp-post-type.php | Registers the post type meta box if a custom callback was specified. |
WP_Post_Type::add_hooks()wp-includes/class-wp-post-type.php | Adds the future post hook action for the post type. |
WP_Customize_Widgets::selective_refresh_init()wp-includes/class-wp-customize-widgets.php | Adds hooks for selective refresh. |
WP_Customize_Selective_Refresh::init_preview()wp-includes/customize/class-wp-customize-selective-refresh.php | Initializes the Customizer preview. |
WP_Customize_Selective_Refresh::enqueue_preview_scripts()wp-includes/customize/class-wp-customize-selective-refresh.php | Enqueues preview scripts. |
WP_Customize_Selective_Refresh::__construct()wp-includes/customize/class-wp-customize-selective-refresh.php | Plugin bootstrap for Partial Refresh functionality. |
rest_api_default_filters()wp-includes/rest-api.php | Registers the default REST API filters. |
WP_Customize_Setting::aggregate_multidimensional()wp-includes/class-wp-customize-setting.php | Set up the setting for aggregated multidimensional values. |
wp_admin_bar_customize_menu()wp-includes/admin-bar.php | Adds the “Customize” link to the Toolbar. |
WP_Widget_Factory::__construct()wp-includes/class-wp-widget-factory.php | PHP5 constructor. |
WP_Customize_Site_Icon_Control::__construct()wp-includes/customize/class-wp-customize-site-icon-control.php | Constructor. |
WP_Customize_Nav_Menu_Item_Setting::__construct()wp-includes/customize/class-wp-customize-nav-menu-item-setting.php | Constructor. |
WP_Customize_Nav_Menus::customize_preview_init()wp-includes/class-wp-customize-nav-menus.php | Adds hooks for the Customizer preview. |
WP_Customize_Nav_Menus::__construct()wp-includes/class-wp-customize-nav-menus.php | Constructor. |
WP_Site_Icon::__construct()wp-admin/includes/class-wp-site-icon.php | Registers actions and filters. |
login_header()wp-login.php | Outputs the login page header. |
Language_Pack_Upgrader::bulk_upgrade()wp-admin/includes/class-language-pack-upgrader.php | Upgrades several language packs at once. |
Theme_Upgrader::install()wp-admin/includes/class-theme-upgrader.php | Install a theme package. |
Theme_Upgrader::upgrade()wp-admin/includes/class-theme-upgrader.php | Upgrades a theme. |
WP_Upgrader::run()wp-admin/includes/class-wp-upgrader.php | Runs an upgrade/installation. |
Plugin_Upgrader::install()wp-admin/includes/class-plugin-upgrader.php | Install a plugin package. |
Plugin_Upgrader::upgrade()wp-admin/includes/class-plugin-upgrader.php | Upgrades a plugin. |
WP_List_Table::__construct()wp-admin/includes/class-wp-list-table.php | Constructor. |
WP_Theme_Install_List_Table::prepare_items()wp-admin/includes/class-wp-theme-install-list-table.php | |
wp_plugin_update_rows()wp-admin/includes/update.php | Adds a callback to display update information for plugins with updates available. |
wp_theme_update_rows()wp-admin/includes/update.php | Adds a callback to display update information for themes with updates available. |
uninstall_plugin()wp-admin/includes/plugin.php | Uninstalls a single plugin. |
add_menu_page()wp-admin/includes/plugin.php | Adds a top-level menu page. |
add_submenu_page()wp-admin/includes/plugin.php | Adds a submenu page. |
WP_Plugin_Install_List_Table::prepare_items()wp-admin/includes/class-wp-plugin-install-list-table.php | |
WP_Internal_Pointers::enqueue_scripts()wp-admin/includes/class-wp-internal-pointers.php | Initializes the new feature pointers. |
Custom_Image_Header::__construct()wp-admin/includes/class-custom-image-header.php | Constructor – Registers administration header callback. |
Custom_Image_Header::init()wp-admin/includes/class-custom-image-header.php | Sets up the hooks for the Custom Header admin page. |
Custom_Background::__construct()wp-admin/includes/class-custom-background.php | Constructor – Registers administration header callback. |
Custom_Background::init()wp-admin/includes/class-custom-background.php | Sets up the hooks for the Custom Background admin page. |
WP_Customize_Manager::customize_preview_init()wp-includes/class-wp-customize-manager.php | Prints JavaScript settings. |
WP_Customize_Manager::setup_theme()wp-includes/class-wp-customize-manager.php | Starts preview and customize theme. |
WP_Customize_Manager::__construct()wp-includes/class-wp-customize-manager.php | Constructor. |
wp_cron()wp-includes/cron.php | Registers _wp_cron() to run on the ‘wp_loaded’ action. |
_custom_header_background_just_in_time()wp-includes/theme.php | Registers the internal custom header and background routines. |
add_thickbox()wp-includes/general-template.php | Enqueues the default ThickBox js and css. |
wp_auth_check_load()wp-includes/functions.php | Loads the auth check for monitoring whether the user is still logged in. |
wp_maybe_load_widgets()wp-includes/functions.php | Determines if Widgets library should be loaded. |
WP_Widget_Recent_Comments::__construct()wp-includes/widgets/class-wp-widget-recent-comments.php | Sets up a new Recent Comments widget instance. |
WP_Embed::__construct()wp-includes/class-wp-embed.php | Constructor |
WP_Admin_Bar::add_menus()wp-includes/class-wp-admin-bar.php | Adds menus to the admin bar. |
WP_Admin_Bar::initialize()wp-includes/class-wp-admin-bar.php | Initializes the admin bar. |
register_activation_hook()wp-includes/plugin.php | Set the activation hook for a plugin. |
register_deactivation_hook()wp-includes/plugin.php | Sets the deactivation hook for a plugin. |
WP_Customize_Setting::preview()wp-includes/class-wp-customize-setting.php | Add filters to supply the setting’s value when accessed. |
WP_Rewrite::flush_rules()wp-includes/class-wp-rewrite.php | Removes rewrite rules and then recreate rewrite rules. |
add_feed()wp-includes/rewrite.php | Adds a new feed type like /atom1/. |
WP_Scripts::__construct()wp-includes/class-wp-scripts.php | Constructor. |
WP_Customize_Header_Image_Control::prepare_control()wp-includes/customize/class-wp-customize-header-image-control.php | |
WP_Customize_Widgets::customize_preview_init()wp-includes/class-wp-customize-widgets.php | Adds hooks for the Customizer preview. |
WP_Customize_Widgets::__construct()wp-includes/class-wp-customize-widgets.php | Initial loader. |
WP_Customize_Widgets::schedule_customize_register()wp-includes/class-wp-customize-widgets.php | Ensures widgets are available for all types of previews. |
wp_set_comment_status()wp-includes/comment.php | Sets the status of a comment. |
_WP_Editors::editor_settings()wp-includes/class-wp-editor.php | |
wp_print_media_templates()wp-includes/media-template.php | Prints the templates used in the media manager. |
Changelog
Version | Description |
---|---|
1.2.0 | Introduced. |
Using with a Class
To use
add_action()
when your plugin or theme is built using classes, you need to use the array callable syntax. You would pass the function toadd_action()
as an array, with$this
as the first element, then the name of the class method, like so:Using with static functions in a class
If the class is called staticly the approach has to be like below as
$this
is not available. This also works if class is extended. Use the following:add_action( 'save_post', array( Classname::class, 'wpdocs_save_posts' ) );
Simple Hook
To email some friends whenever an entry is posted on your blog:
To pass a variable to the called function of the action, you can use closures (since PHP 5.3+) when the argument is not available in the original coded do_action. For example:
$myvar = 'Hello World'; $action_wp_footer = function($arguments) use ($myvar) { echo $myvar; }; add_action('wp_footer', $action_wp_footer, 100, 1);
which can be removed with:remove_action('wp_footer', $action_wp_footer, 100);
with the advantage that typos in the closure name will yeild a helpfull Undfined variable error on typos.Related:
do_action()
remove_action()
Passing parameters while using in a Class
To pass parameters to your method in a Class while calling it with add_action, you can do as following:
I urge you, don’t attach your hook callbacks inside class’ constructor.
Instead of implementing official example most upvoted in this thread, opt for decoupled solution. You have one more line of code to write, but objects become more reusable and less error-prone (consider, what would happen if you call
new WP_Docs_Class()
twice in your code, following Codex example).How to add an action that calls a function (with parameters) from an instantiated class:
Accepted Arguments
A hooked function can optionally accept arguments from the action call, if any are set to be passed. In this simplistic example, the
echo_comment_id
function takes the$comment_id
argument, which is automatically passed to when thedo_action()
call using thecomment_id_not_found
filter hook is run.To prevent runtime errors due to easy typo errors (defensive programming) and prevent pollution of the global namespace use closures instead of function names. The sample code adjusted: