Deb*_*ler 4 php wordpress templates
我现在正在开发一个 WordPress 主题,想知道是否有一个选项可以知道页面是否正在使用模板文件?我需要该页面的链接...谢谢!
小智 5
函数get_page_template_slug( $post_id )将返回当前分配的页面模板的 slug(如果未分配模板,则返回空字符串 - 如果 $post_id 与实际页面不对应,则返回 false)。您可以在任何地方(在 The Loop 中或外部)轻松使用它来确定是否为任何页面分配了页面模板。
is_page_template(); 当使用模板时,函数将返回 true。您还可以传递文件名来检查是否应用了特定模板。
if ( is_page_template('about.php') ) {
// Returns true when 'about.php' is being used.
} else {
// Returns false when 'about.php' is not being used.
}
Run Code Online (Sandbox Code Playgroud)
还有一种方法。您可以使用 get_post_meta 来获取应用模板的值。
global $post;
get_post_meta($post->ID,'_wp_page_template',true);
Run Code Online (Sandbox Code Playgroud)
小智 5
之前建议的答案不会让你得到你想要的。它只会显示当前页面或您指定的页面正在使用该模板,而不会找到任何正在使用该模板的页面。
如果您想实际搜索以查看是否有任何页面正在使用模板,您可以进行查询。meta_query 不是最有效/最快的,但取决于您正在构建的内容可能不会成为问题。
$query = new WP_Query(
array(
'post_type' => 'page',
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => '_wp_page_template',
'value' => 'your-template.php',
),
),
)
);
if ( $query->have_posts() ) {
/* There is a match so either start the loop and use get_the_permalink() to get the link or make a foreach loop and get the ids of the items and get_the_permalink($id) */
}
Run Code Online (Sandbox Code Playgroud)