WordPress插件中替代get_template_part输出PHP文件的方法
解决插件中get_template_part无法加载模板的替代方案
get_template_part默认只会在主题/子主题目录中搜索模板文件,所以你把cc-archive.php放到插件目录后,它依然找不到,自然无法生效。下面是两种实用的替代方法:
方法一:直接用include/require加载插件模板
直接通过插件目录路径定位到模板文件,用include引入,同时传递需要的变量:
function my_couse_cards($atts) { ob_start(); $cat = $atts['id']; // 获取当前插件的绝对目录路径,拼接模板文件名 $template_file = plugin_dir_path(__FILE__) . 'cc-archive.php'; // 把需要的变量传递给模板,模板里直接用$catid即可 $catid = $cat; include $template_file; return ob_get_clean(); }
方法二:自定义支持插件路径的模板加载函数
如果想保留类似get_template_part的灵活性(比如允许主题覆盖插件模板),可以自己写一个模板加载函数,优先从主题目录找,找不到再用插件里的:
步骤1:定义自定义模板加载函数
function my_plugin_get_template_part($slug, $name = null, $args = array()) { // 先尝试在主题/子主题目录查找模板 $template = locate_template(array( "{$slug}.php", $name ? "{$slug}-{$name}.php" : '' )); // 主题里找不到,就用插件目录的模板文件 if (!$template) { $template_path = plugin_dir_path(__FILE__); $template = $template_path . ($name ? "{$slug}-{$name}.php" : "{$slug}.php"); } // 将参数提取为模板可用的变量 if (!empty($args) && is_array($args)) { extract($args); } include $template; }
步骤2:在短代码中调用自定义函数
function my_couse_cards($atts) { ob_start(); $cat = $atts['id']; my_plugin_get_template_part( 'cc-archive', null, array( 'catid' => $cat ) ); return ob_get_clean(); }
内容的提问来源于stack exchange,提问作者Akash Talele
相关产品推荐
相关产品推荐

