Sign up ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

When looking through WordPress snippets/tutorials/plugins I often see add_action() and add_filter() being placed before the function is declared:

add_action( 'publish_post', 'email_friends' );

function email_friends( $post_ID ) {
   $friends = ',';
   mail( $friends, "sally's blog updated" , 'I just put something on my blog:' );
   return $post_ID;

From a logic standpoint this just doesn't make sense to me. Why would you place the function after it is called in your code? This is usually how I would handle the same situation:

function email_friends( $post_ID )  {
   $friends = ',';
   mail( $friends, "sally's blog updated" , 'I just put something on my blog:' );
   return $post_ID;

add_action( 'publish_post', 'email_friends' );

I know both scenarios work, but is there a specific advantage to one or the other? About 90% of the time I see the first scenario being used, so that leads me to believe there is a benefit to this in some way.

share|improve this question

2 Answers 2

up vote 6 down vote accepted

It is easier to read: When is what called? If you are debugging a hook you can immediately see if you have to read the function or not: If it is not your hook, you can skip the code.

In my themes and plugins I combine all registrations for actions, filters and shortcodes at the top and I add the hook to the PHPDoc block:

add_action( 'wp_head',  'foo' );
add_action( 'shutdown', 'bar' );

 * Foo you!
 * @wp-hook wp_head
 * @return  void
function foo()
    print '<!-- foo -->';
share|improve this answer
Although I don't agree (Just because of my personal preference and past coding practices) that its easier to read this does make sense as to why it's done in this manner. Thank you for the answer Toscho! – voodooGQ Sep 26 '12 at 18:19

There is no real difference actually, I for example prefer to follow first scenario, because it's neater to place calls in one place, and define functions below that. PHP parses the whole document prior to running anything, and if functions are properly defined, everything will work normally, no advantage in either scenario.

I believe the right saying here is: Whatever floats your boat :)

share|improve this answer
It works not because PHP parses the whole document, but because call_user_func_array() is (most likely) called after your function definition when running do_action. So you can define the hooked function anywhere up to that point. – kovshenin May 4 at 10:39

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.