Do custom hooks that hook onto wordpress core get executed automatically by wordpress or do we have to call the do_action
function on the custom made hook ourselves?
Example:
add_action("action_one","some_process",10);
add_action("action_one","some_different_process",11);
function some_process(){ //... }
function some_different_process(){ //... }
do_action("action_one");
Does some_process
get executed first and then some_different_process
gets executed after when do_action("action_one")
is called?
If you create custom action hooks that exist within your custom theme or plugin, then yes, you have to call them via
do_action
in the appropriate location where you would want them to be triggered.WordPress does not automatically find action hooks and trigger them. It has a number of built-in hooks which you can latch onto in order to run custom code, but if you create your own hooks, then you need to also set up the appropriate
do_action
call in order to run them.To answer your other question regarding the execution order of
some_process
andsome_different_process
,some_process
will be run beforesome_different_process
because it had a lower priority number.If you want an action to run early, give it a low number like 1 or 5, if you don’t care where it runs or want it to run last, I usually use a much higher number like 100 or 1000. If two hooks are defined with the same priority, usually the one that got registered first will run before the other one with the same priority.
All functions that are hooked onto an action are automatically executed IF that action is called, but they are not called if the action is not triggered.
For example if you have:
Then
some_function
will be called ifaction_one
is triggered. Ifaction_one
is never triggered, some_function is not called.do_action
is a mechanism to manually trigger the action, though keep in mind it will trigger ANY hooks into that action, not just yours (unless you setup some filters).Another example: let’s say you setup a custom function to run on the action
save_post
:Then every time you a save a post your
top_secret_function
will run.If you want to trigger
save_post
manually (without actually saving a post) you can do so with:and it will trigger your
top_secret_function
, but this would generally not be recommended because it will also trigger any other function that is hooked intosave_post
(which many plugins and core files do).You can setup custom actions using a combination of
add_action
anddo_action
.