要获取使用特定页面模板的页面ID,你可以使用WordPress的get_page_templates()
函数以及get_posts()
函数。
以下是一个示例代码:
// 获取所有页面模板 $templates = get_page_templates(); // 指定你想要查找的模板名称 $template_name = 'templatename.php'; // 初始化一个变量来存储匹配的页面ID $matched_page_id = null; // 循环遍历所有页面模板 foreach ($templates as $template_name => $template_file) { if ($template_file === $template_name) { // 使用 get_posts 函数查找具有特定模板的页面 $args = array( 'post_type' => 'page', 'meta_key' => '_wp_page_template', 'meta_value' => $template_name ); $pages = get_posts($args); // 如果找到匹配的页面,将页面ID存储在变量中 if (!empty($pages)) { $matched_page_id = $pages[0]>ID; break; } } } // 检查是否找到匹配的页面ID if ($matched_page_id) { echo "使用模板 $template_name 的页面ID是: $matched_page_id"; } else { echo "未找到使用模板 $template_name 的页面"; }
在上述代码中,你需要将templatename.php
替换为你要查找的页面模板的名称。这段代码会首先获取所有页面模板,然后循环遍历它们,查找使用特定模板的页面。如果找到匹配的页面,它会将页面ID存储在$matched_page_id
变量中。
请确保将这段代码添加到你的WordPress主题的functions.php
文件中或者将其包含在主题文件中。