Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Grab the page id for the first page using a specific template. Ideal for situations with a template intended for a only one page.
<?php
/**
* Get the first page id with the matching template slug.
*
* @author Joshua David Nelson, josh@joshuadnelson.com
*
* @param string $template This is the template slug, like 'template-about-page.php'
*
* @return mixed $page_id Int or false on failure
*/
if( !function_exists( 'get_page_id_by_template' ) ) {
function get_page_id_by_template( $template ) {
$args = array(
'post_type' => 'page',
'fields' => 'ids',
'post_status' => 'publish',
'nopaging' => true,
'posts_per_page' => 1,
'update_post_term_cache' => false,
'meta_key' => '_wp_page_template',
'meta_value' => esc_attr( $template ),
);
$pages = get_posts( $args );
$page_id = isset( $pages[0] ) ? $pages[0] : false;
return $page_id;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.