Tuesday, April 7, 2015

Wordpress - do_action and add_action

Wordpress has many hooks, among which do_action and add_action are most significant. Guys who are beginners to wordpress really needs to know the difference between this two hooks. Because this plays the vital role in creating plugins. Lets know what is the basic difference between do_action and add_action.

do_action 

Allows you to create a new action. This is much like apply_filters() with the exception that nothing is returned and only the functions or methods are called.
<?php do_action( $tag, $arg ); ?>



add_action

Allows you to hook a function on to a pre-existing action. This function is an alias to add_filter().
<?php add_action( $hook, $function_to_add, $priority, $accepted_args ); ?>

A plugin might use do_action to create its own custom "hook" and then add functions to that hook in various scripts via add_action.

Example:

do_action( 'publish_post', $post_ID, $post, $update ); 

function example_save_post( $post_ID, $post, $update ) {
  // do your stuff here
  
  return $post_ID;
}
add_action( 'publish_post', 'example_save_post', 10, 3 );

Here, publish_post is an action triggered whenever a post is published, or when the status is changed to publish. So on publishing post you can use add_action to do some stuff for your post. Say, sending mail to your users about the post.




No comments:

Post a Comment