为了使模板能够正常工作,我们需要能够在调用它们时找到正确的模板。使用以下代码,插件首先在themes/your-theme/woocommerce-plugin-templates/{template-name} 中查找被调用的模板文件,如果找不到,它将在您的主主题文件themes/your-theme/{template-name} 中搜索并回退到plugins/woocommerce-plugin-templates/templates/{template-name} 中的原始插件模板。
<?php
/**
* Locate template.
*
* Locate the called template.
* Search Order:
* 1. /themes/theme/woocommerce-plugin-templates/$template_name
* 2. /themes/theme/$template_name
* 3. /plugins/woocommerce-plugin-templates/templates/$template_name.
*
* @since 1.0.0
*
* @param string $template_name Template to load.
* @param string $string $template_path Path to templates.
* @param string $default_path Default path to template files.
* @return string Path to the template file.
*/
function wcpt_locate_template( $template_name, $template_path = '', $default_path = '' ) {
// Set variable to search in woocommerce-plugin-templates folder of theme.
if ( ! $template_path ) :
$template_path = 'woocommerce-plugin-templates/';
endif;
// Set default plugin templates path.
if ( ! $default_path ) :
$default_path = plugin_dir_path( __FILE__ ) . 'templates/'; // Path to the template folder
endif;
// Search template file in theme folder.
$template = locate_template( array(
$template_path . $template_name,
$template_name
) );
// Get plugins template file.
if ( ! $template ) :
$template = $default_path . $template_name;
endif;
return apply_filters( 'wcpt_locate_template', $template, $template_name, $template_path, $default_path );
}
上面的代码定位并返回一个现有的有效路径,该路径可以加载并包含在页面上。为了实际获取模板文件,有一个额外的功能。下面的代码可以直接在简码函数中使用来加载文件。
<?php
/**
* Get template.
*
* Search for the template and include the file.
*
* @since 1.0.0
*
* @see wcpt_locate_template()
*
* @param string $template_name Template to load.
* @param array $args Args passed for the template file.
* @param string $string $template_path Path to templates.
* @param string $default_path Default path to template files.
*/
function wcpt_get_template( $template_name, $args = array(), $tempate_path = '', $default_path = '' ) {
if ( is_array( $args ) && isset( $args ) ) :
extract( $args );
endif;
$template_file = wcpt_locate_template( $template_name, $tempate_path, $default_path );
if ( ! file_exists( $template_file ) ) :
_doing_it_wrong( __FUNCTION__, sprintf( '<code>%s</code> does not exist.', $template_file ), '1.0.0' );
return;
endif;
include $template_file;
}
此代码将使用wcpt_locate_template() 函数查找并返回有效模板文件的路径,当没有找到有效的模板文件并且模板文件不存在于插件的模板文件夹中时,这种情况永远不会发生,将显示错误。