I am trying to find what exactly do_action and add_action works. I already examine with add_action but for do_action i am trying as new now. This what i tried.
function mainplugin_test() {
$regularprice = 50;
if(class_exists('rs_dynamic')) {
$regularprice = 100;
}
// and doing further
//like i echoing the regular price
echo $regularprice; //It print 100 from this code
}
Now instead of placing few code in main file i am planning to create do_action to avoid code messing issue.
function mainplugin_test() {
$regularprice = 50;
do_action('testinghook');
// and doing further
//like i echoing the regular price
echo $regularprice; //It should print 100 but it print 50
}
so i created another function to point out that hook as something like
function anothertest() {
if(class_exists('rs_dynamic')) {
$regularprice = 100;
}
}
add_action('testinghook','anothertest');
Not sure how to add the lines of code to that hook that above function may work? As per i tried in my testing environment nothing helps. If i understand correct do_action is more like including a file??? If not please advise me.
Thanks.
do_action
creates an action hook,add_action
executes hooked functions when that hook is called.For example, if you add the following in your theme’s footer:
You can echo content at that location from functions.php or a custom plugin:
You can also pass variables to a hook:
Which you can use in the callback function:
In your case, you’re probably trying to filter the value based on a condition. That’s what filter hooks are for:
Reference
Edit (updated references links)
The reason it didn’t print
100
, because$regularprice
withinanothertest()
function is local to that function. The variable$regularprice
used in parentmainplugin_test()
function is not same as the variable used inanothertest()
function, they are in separate scope.So you need to either define the
$regularprice
in a global scope (which is not a good idea) or you can pass argument as a parameter todo_action_ref_array
. Thedo_action_ref_array
is the same asdo_action
instead it accepts second parameter as array of parameters.Passing as argument:
Actually, the
add_action
is an action hook which is used to invoke an action (a registered handler) on a certain point depending on the action and thedo_action
is used to manually invoke that registered action. For example:This handler will be invoked when you take or the script does the
some_action
but if you want you may invoke that action manually using thedo_action
. So, basically thedo_action
invokes the registered action hook when you call it. Check more on Codex.//with do_action we create own tag(hook) use in wordpress
Ex. Here I added 1 custom function to call this
In add_action I added function name with any custom tag name
With do_action(my custom tag name)
—add_action()—
hook-specific hook that will affect by function()
It will change functionality and behaviour of wordpress by Specific âhookâ we can change it and functions method.