Wordpress - Get page id by template
When a page is created, the assigned template to that page is saved as custom post meta in the same way as custom fields. The meta_key
is _wp_page_template
and the meta_value
will be the page template
You can simply make use of get_pages
to retrieve all pages which have a meta_value
of the specified template
$pages = get_pages(array(
'meta_key' => '_wp_page_template',
'meta_value' => 'page-special.php'
));
foreach($pages as $page){
echo $page->ID.'<br />';
}
EDIT 23-07-2015
If one just needs the page ids, then you make use of get_posts
and then just pass page
as post_type
and 'idsas
fields` value. This will ensure a much faster, much more optimized query as we will only return the post id column in the db and not all of them for the given pages
(Requires 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>';
If your page template resides inside sub-folder, theme-folder/page-templates/page-template.php then you below query will works:
$page_details = get_pages( array(
'post_type' => 'page',
'meta_key' => '_wp_page_template',
'hierarchical' => 0,
'meta_value' => 'page-templates/page-template.php'
));
This above codes also display sub-pages as well.
Thanks