这是WordPress中的默认get\\u template\\u part函数:
function get_template_part( $slug, $name = null ) {
do_action( "get_template_part_{$slug}", $slug, $name );
$templates = array();
if ( isset($name) )
$templates[] = "{$slug}-{$name}.php";
$templates[] = "{$slug}.php";
locate_template($templates, true, false);
}
我正在尝试使用该操作从插件中查找自定义post类型循环文件:
add_action( "get_template_part_templates/loop", function($slug, $name){
if ("example" == $name){
if (!locate_template("templates/loop-{$name}.php", false, false)){
/* What do you suggest to do here? */
}
}
},10,2 );
我需要一个解决方案;
检查主题是否有“示例”自定义帖子类型的文件,如果没有;使用插件的模板文件显示,不要使用主题的默认解决方案Update: 这是在主题中调用模板部分的代码:
global $post;
get_template_part( \'templates/loop\', $post->post_type );
SO网友:user36382
/**
*Extend WP Core get_template_part() function to load files from the within Plugin directory defined by PLUGIN_DIR_PATH constant
* * Load the page to be displayed
* from within plugin files directory only
* * @uses mec_locate_admin_menu_template() function
* * @param $slug * @param null $name
*/
function mec_get_admin_menu_page($slug, $name = null) {
do_action("mec_get_admin_menu_page_{$slug}", $slug, $name);
$templates = array();
if (isset($name))
$templates[] = "{$slug}-{$name}.php";
$templates[] = "{$slug}.php";
mec_locate_admin_menu_template($templates, true, false);
}
/* Extend locate_template from WP Core
* Define a location of your plugin file dir to a constant in this case = PLUGIN_DIR_PATH
* Note: PLUGIN_DIR_PATH - can be any folder/subdirectory within your plugin files
*/
function mec_locate_admin_menu_template($template_names, $load = false, $require_once = true )
{
$located = \'\';
foreach ( (array) $template_names as $template_name ) {
if ( !$template_name ) continue;
/* search file within the PLUGIN_DIR_PATH only */
if ( file_exists(PLUGIN_DIR_PATH . \'/\' . $template_name)) {
$located = PLUGIN_DIR_PATH . \'/\' . $template_name;
break;
}
}
if ( $load && \'\' != $located )
load_template( $located, $require_once );
return $located;
}
然后使用
mec_get_admin_menu_page($slug, $name = null);
在插件文件中的任意位置运行,如
get_template_part($slug, $name = null)
作用
mec_get_admin_menu_page(\'custom-page\',\'one\');
上述示例函数将查找
custom-page-one.php
在您的
PLUGIN_DIR_PATH
并加载它。
此外,我建议您使用:
define(\'PLUGIN_DIR_PATH\', plugin_dir_path(__FILE__));
定义插件目录路径。