What’s the difference between do_action and add_action in WordPress ?

  • Update On January 6th, 2017
  • in WordPress

This post was last updated on January 6th, 2017 at 07:16 pm

do_action( string $tag, $arg = '' )

This function invokes all functions attached to action hook $tag. It is possible to create new action hooks by simply calling this function, specifying the name of the new hook using the $tag parameter. You can pass extra arguments to the hooks.

add_action( string $tag, callable $function_to_add, int $priority = 10, int $accepted_args = 1 )

Executes hooked functions when that hook is called at specific points during execution, or when specific events occur.

For example, if you add the following in your theme’s footer:

do_action( 'my_footer_hook' );

You can echo content at that location from functions.php or a custom plugin:

add_action( 'my_footer_hook', 'my_footer_echo' );
function my_footer_echo(){
    echo 'hello world';
}

You can also pass variables to a hook:

do_action( 'my_footer_hook', home_url( '/' ) );

Which you can use in the callback function:

add_action( 'my_footer_hook', 'my_footer_echo', 10, 1 );
function my_footer_echo( $url ){
    echo "The home url is $url";
}
About This Author

My name is Parameshwar Roy (P. Roy), and I am a web developer. This is my personal blog to record my own thoughts. Though I am not a natural writer, I love to share my experiences. Hope my experiences will be useful to you...read more about me

Leave A Reply