如何获取页面模板名称?例如模板名称:模板名称

Mil*_*lan 5 php wordpress

有没有办法获取页面模板的名称?
我的意思是在页面模板中,我们在开头写Template Name: template name
I Want " template name" by page-id

我已经尝试过get_post_meta(get_the_ID(), '_wp_page_template', true) and get_page_template_slug($post_id),但没有任何功能有帮助

小智 6

有一个更合适的方法可以做到这一点。说我们已经有了模板路径:

$template_path = get_post_meta(get_the_ID(), '_wp_page_template', true);
Run Code Online (Sandbox Code Playgroud)

然后我们就这样做:

$templates = wp_get_theme()->get_page_templates();
echo $templates[$template_path];
Run Code Online (Sandbox Code Playgroud)

它输出模板名称。就如此容易。


Mil*_*lan 0

我已经想通了。
因为我将在 WordPress 管理中使用,所以我使用了正则表达式。
是这样的preg_match('/\bTemplate Name: [a-zA-Z0-9\s\-_]+\b/',$file,$template);
$file文件名来自get_post_meta(get_the_ID(), '_wp_page_template', true)

它给了我Template Name: template name,然后我使用一些数组函数从返回的数组中获取实际部分preg_match

我希望这个解决方案将来能够帮助其他开发人员。