Answers:
创建页面后,对该页面分配的模板将以与自定义字段相同的方式另存为自定义帖子元。该meta_key
是_wp_page_template
与meta_value
将页面模板
您可以简单地利用get_pages
来检索所有具有meta_value
指定模板的页面
$pages = get_pages(array(
'meta_key' => '_wp_page_template',
'meta_value' => 'page-special.php'
));
foreach($pages as $page){
echo $page->ID.'<br />';
}
如果仅需要页面ID,则可以使用as ,get_posts
然后传递page
as post_type
和“ ids as
字段”值。这将确保更快,更优化的查询,因为我们将只返回db中的post id列,而不是给定页面的所有id
(需要PHP 5.4+)
$args = [
'post_type' => 'page',
'fields' => 'ids',
'nopaging' => true,
'meta_key' => '_wp_page_template',
'meta_value' => 'page-special.php'
];
$pages = get_posts( $args );
foreach ( $pages as $page )
echo $page . '</br>';
set_transient
(codex.wordpress.org/Transients_API)。
如果您的页面模板位于子文件夹theme-folder / page-templates / page-template.php内,则下面的查询将起作用:
$page_details = get_pages( array(
'post_type' => 'page',
'meta_key' => '_wp_page_template',
'hierarchical' => 0,
'meta_value' => 'page-templates/page-template.php'
));
上面的代码也显示子页面。
谢谢
以下是更加明确的脚本,其中考虑了语言(如果需要)。注意,它假定使用Polylang,而不是WPML。
function get_post_id_by_template($template,$lang_slug = null){
global $wpdb;
$wh = ($lang_slug) ? " AND t.slug = %s" : "";
$query = $wpdb->prepare(
"SELECT DISTINCT p.ID
FROM $wpdb->posts p
INNER JOIN $wpdb->postmeta meta ON meta.post_id = p.ID
INNER JOIN $wpdb->term_relationships tr ON meta.post_id = tr.object_id
INNER JOIN $wpdb->term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
INNER JOIN $wpdb->terms t ON tt.term_id = t.term_id
WHERE p.post_status = 'publish' AND meta.meta_key = %s AND meta.meta_value = %s" . $wh,
'_wp_page_template',
$template,
$lang_slug
);
$ids = $wpdb->get_results($query);
if($ids && isset($ids[0])){
$p = $ids[0];
return $p->ID;
} else {
return false;
}
}// get_post_id_by_template
这是与WPML和Polylang一起使用的完整功能。归功于https://github.com/cyrale/
/**
* Search for a page with a particular template.
*
* @param string $template Template filename.
* @param array $args (Optional) See also get_posts() for example parameter usage.
* @param bool $single (Optional) Whether to return a single value.
*
* @return Will be an array of WP_Post if $single is false. Will be a WP_Post object if the page is find, FALSE otherwise
*/
if (!function_exists('get_page_by_template')) {
function get_page_by_template($template, $args = array(), $single = true) {
$pages_by_template = wp_cache_get('pages_by_template', 'cyrale');
if (empty($pages_by_template) || !is_array($pages_by_template)) {
$pages_by_template = array();
}
if (!isset($pages_by_template[$template])) {
$args = wp_parse_args(array(
'posts_per_page' => -1,
'post_type' => 'page',
'suppress_filters' => 0,
'meta_query' => array(
array(
'key' => '_wp_page_template',
'value' => $template,
),
),
), $args);
$pages = get_posts($args);
$pages_by_template[$template]= array(
'single' => !empty($pages) && is_array($pages) ? reset($pages) : false,
'pages' => $pages,
);
}
wp_cache_set('pages_by_template', $pages_by_template, 'cyrale');
return $pages_by_template[$template][$single ? 'single' : 'pages'];
}
}