Action hooks allow us to make our plugins much more extensible, and some times we need to be able to check whether a hook exists, or has been registered. We might need to check that a hook exists for a variety of reason, and thankfully WordPress gives us a really easy way to do that. Using the has_action() function, we can run functions conditionally, based on whether our specified hook exists.

The has_action() conditional works just like the has_filter(): we simply pass the name of the action we want to check for. Like this:

1
2
3
4
5
6
if(has_action('name_of_action_to_check_for')) {
	// action exists so execute it
	do_action('name_of_action_to_check_for');
} else {
	// action has not been registered
}

This has a lot of real world applications. I just used it today in my Easy Content Types to output some special field-type-specific information. I needed to check that the action hook for each individual field type was registered, output the information from the hook if it was, and then display default information for any field type without an action registered. The way that I used it was like this:

1
2
3
4
5
6
7
 
<?php 
if(has_action('ecpt_field_options_' . $field->type)) {
	do_action('ecpt_field_options_' . $field->type, $field); 
} else { ?>
	<p class="description">No options for this field</p>
<?php } ?>

This conditional runs for every meta field type registered in the plugin. $field->type refers to the type of field, so for my “textarea” field, the hook is named ecpt_field_options_textarea. By doing it this way, I can very easily specify custom HTML for each field type (including those registered through add-on plugins), while still displaying default information for fields without a hook registered.

Pretty cool right?

This is actually very similar to the way the wp_ajax_ hook works, which you will see if you go explore the WordPress core admin-ajax.php file.

  1. chuck scott

    Hey Pippin – just wanted to leave appreciative comment and say, “THANKS” for this post … i was knocking my head around with “if function_exists” when trying to determine if an action was present and was only after googling around a bit and came across your excellent post on using if has_action (and/or has_filter) which helped crack the code (sorry, pun slightly intended) … accordingly, best of ongoing success with all things WP et al. :>) cheers – chuck scott

    • Pippin

      Great to hear!

  2. Abdulrahman Hariri

    Hi,

    I was looking for this as well and was able to land on your site quickly :). Thanks a lot!

  3. Oleh Odeshchak

    You can’t check to see if a action exists reliably.

    Because the only time the action exists is when to do_action is called or someone else adds actions to it.

    So the action only exists when someone adds a action to it, or the action is called.

    And if someone adds actions, it doesn’t guarantee the action will be called at all.

Comments are closed.