Wordpress - Difference between do_action and add_action

Use do_action( 'unique_name' ) to create your own actions.

You can use that to offer an API for your plugin, so other plugins can register callbacks for your custom action. Example: Do I need to call do_action in my plugin?

But you can use custom actions (or filters) in a theme too. Example: Best practice way to implement custom sections into a WordPress theme

And you can combine both to make a plugin and a theme working together. Example: How to make method from plugin available in theme?

Summary: add_action( 'foo' ) registers a callback, do_action( 'foo' ) executes that registered callback.


This is my guess, so if you know better, please make a comment so I can update my guess.

Your plugin code is executed before wp_head() (which we can assume will invoke the actions added to it). When you add_action('wp_head','custom_register'), you are telling PHP that when (in the future) do_action('wp_head') is called, to call custom_register() as well. The same is true of your call to add_action('custom','custom_register') but as you see in your code, the call to do_action('custom') has already been made, and when it was called, there was not (yet) any action added to it. This is why Toscho asked what happens when you call do_action('custom') after you registered the callback. Your answer about back end and front end is ambiguous. If you swap the last two lines in the following code, I think it will work:

function custom_register()
{
    echo '<script>jQuery(document).ready(function(){alert("Learning Hooks");});</script>';

}
do_action('custom');                    // This is called before it will have an effect.

add_action('custom','custom_register'); // Too late - do_action was already called.

Tags:

Actions

Hooks