Skip to content

Instantly share code, notes, and snippets.

@tyxla
Last active August 29, 2015 14:08
Show Gist options
  • Save tyxla/a1539561803de4d03c11 to your computer and use it in GitHub Desktop.
Save tyxla/a1539561803de4d03c11 to your computer and use it in GitHub Desktop.
Get a page by its template, and optionally by additional criteria
<?php
# Get a page by its template, and optionally by additional criteria
function crb_get_page_by_template($template, $additional_meta = array()) {
// the query for the page template
$meta_query = array(
array(
'key' => '_wp_page_template',
'value' => $template,
)
);
// if there is an additional criteria, merge with the above meta query
if ($additional_meta) {
$meta_query = array_merge($meta_query, $additional_meta);
$meta_query['relation'] = 'AND';
}
// perform the query
$pages = get_posts(array(
'post_type' => 'page',
'posts_per_page' => 1,
'orderby' => 'ID',
'order' => 'ASC',
'meta_query' => $meta_query
));
// get the first page only
if ($pages && !empty($pages[0])) {
return $pages[0];
}
return false;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment