I’m a newbie in WordPress and I need a big help to understand how do-action works.
It seems there is a relationship between the instruction do_action
and the code that follows it in the get_xxx function that I don’t understand. For example, in the following function :
function get_header( $name = null ) {
do_action( 'get_header', $name );
$templates = array();
$name = (string) $name;
if ( '' !== $name ) {
$templates[] = "header-{$name}.php"; // instruction 1
}
$templates[] = 'header.php'; // instruction 2
locate_template( $templates, true );
}
There is a do_action
at the beginning to find header.php
. Then afterwards, a series of codes are doing the same thing but with likely an issue because the content of the variable $templates
of the line “instruction 1” is always overridden by the one in the line of “instruction 2” because it is not a “if then else”.
In every function get_xxxx we have the same structure. I guess there is a relationship between the do_action
call and the series of codes that follow but I don’t get it.
I will be very grateful if somebody can help me to understand this issue.
1 Answer
The do_action
:
do_action( 'get_header', $name );
its triggering the action get_header
, so all actions attached using add_action
to the action 'get_header'
will be executed, its also passing the $name
as parameter to the functions by example:
function my_function($name){
echo "The Action sent me the name:".$name."!!";
}
add_action('get_header', 'my_function');
when the do_action( 'get_header', $name );
is executed my_function
will be called with $name
as a parameter, this way you can do “something” before the header template is loaded.
instruction 2
is not overriding instruction 1
its adding the default 'header.php'
to the array as a fallback, if you are calling a custom header the $templates
array will be like this (using get_header('custom');
):
Array
(
[0] => header-custom.php
[1] => header.php
)
locate_template will try to find and load with require_once
the first template, if it doesnt exist or it cant find it, it will fallback to header.php
and try to load that one too.