Home > Article > Backend Development > Analysis of related PHP functions used to retrieve templates in WordPress
locate_template() is used to retrieve the existing template file with the highest priority, and can also directly load the template file.
When the locate_template() function is used to retrieve, if there is a child theme, the template of the child theme will be used first, and the parent theme will not be searched again.
Usage
locate_template( $template_names, $load, $<strong>require</strong>_once );
Parameters
$template_names
(array) (required) The template file name to be imported (requires extension), will match whether the file exists one by one according to the array, the higher the priority, the higher the priority.
Default value: None
$load
(Boolean) (optional) If set to True, the template file will be imported directly.
Default value: False
$require_once
(Boolean) (optional) If set to True, if it has been introduced before, it will not be introduced this time (require_once), otherwise it will be introduced regardless of whether it has been introduced before. (require).
(This parameter only takes effect if $load is True).
Default value: False
Return value
(String) As long as a specified template file exists, return its path, otherwise return an empty string.
Example
if( locate_template( 'content-' . $pageName . '.php' ) !== '' ){ //存在,引入模板文件 get_template_part( 'content', $pageName ); }else{ //不存在,直接显示内容 the_content(); }
Others
This function is located at: wp-includes/template.php
Quickly retrieve the template
get_query_template() is used to quickly retrieve the page template, and it needs to be according to the predetermined page type (type) .
The difference between it and locate_template() is that you need to fill in the type of the page, and the {$type}_template template path filter will be generated.
Usage
get_query_template( $type, $templates );
Parameters
$type
(string) (required) The type of page of the template file to be obtained, fill in the file name of the corresponding template file without extension (such as single).
Default value: None
$templates
(array) (optional) A list of alternative templates.
Default value: empty array
Return value
Returns the path to the template file.
Example
Introduce the template of the 404 page if it exists:
if ( '' != get_404_template() ) include( get_404_template() );
Others
This function is located at: wp-includes/template.php
The above introduces the analysis of the relevant PHP functions used to retrieve templates in WordPress, including the require content. I hope it will be helpful to friends who are interested in PHP tutorials.