Reputation: 294
When we create a function to hook with a action or filter hook in Wordpress, we may need some parameter to pass into the function, since we are not manually calling the function. Rather, the action or filter hook will call it when needed.
How we will pas all necessary parameter to the function? Does the action or filter hook provide some parameter when it call any function ? If yes, what is the way to know about all the parameter that any action or filter hook has?
Upvotes: 1
Views: 5002
Reputation: 15855
To read about hook documentation, see http://codex.wordpress.org/Plugin_API/Filter_Reference and http://codex.wordpress.org/Plugin_API/Action_Reference. These two sites will tell you about the number and type of parameters passed by wordpress when the hook (action or filter) is called.
Or you can look at the wordpress source itself. If you're using an IDE like WebStorm then you can do an Edit->Find->Find in Path and search for the hook name to find examples and the source where the hook is called.
For example, to add a logout action, see function wp_logout()
in pluggable.php
. The line do_action('wp_logout');
shows you where the action is called and what parameters are passed (in this case, none).
/**
* Log the current user out.
*
* @since 2.5.0
*/
function wp_logout() {
wp_destroy_current_session();
wp_clear_auth_cookie();
/**
* Fires after a user is logged-out.
*
* @since 1.5.0
*/
do_action( 'wp_logout' );
}
endif;
Then, to add a custom action to be called at do_action('wp_logout');
, in your theme's functions.php, add this
add_action('wp_logout', 'my_on_logout');
function my_on_logout() {
// do what you want to do
echo 'hi mom';
}
If you see from the do_action
or do_filter
or from the documentation the hook has parameters, then you specify them in the fourth argument of your add_action
or add_filter
, like so. The 2
below means that there two parameters to be passed to the publish_product
action: ($post_id, $post)
add_action('publish_product', 'my_on_product_update', 10, 2);
**
* do something when a product is created
* @param int $post_id the post id
* @param WP_Post $post not used
*/
function my_on_product_update($post_id, $post) {
// do action
echo 'hi dad';
}
Upvotes: 2
Reputation: 994
You cannot pass arguments via add_action
. However, you can do this with do_action
From wp documentation:
<?php do_action( $tag, $arg ); ?>
$arg
is the argument that you can pass.
So, you could do something like:
add_action( 'your_custom_action', 'your_function' );
...
do_action( 'your_custom_action', $your_arguments );
Upvotes: 4