Skip to content

Instantly share code, notes, and snippets.

@morgyface
Last active August 27, 2019 10:32
Show Gist options
  • Select an option

  • Save morgyface/c088e55381133388c0e150060c7711ec to your computer and use it in GitHub Desktop.

Select an option

Save morgyface/c088e55381133388c0e150060c7711ec to your computer and use it in GitHub Desktop.
WordPress | Get the ID of the first page using a specific template
<?php
// Get the ID of the first page using a specific template
function page_id_from_template( $template_name ) {
$args = array(
'post_type' => 'page',
'fields' => 'ids',
'nopaging' => true,
'meta_key' => '_wp_page_template',
'meta_value' => $template_name
);
$template_pages = get_posts( $args );
if( $template_pages ) {
$first_id = reset($template_pages);
return $first_id;
} else {
return null;
}
}
?>
@morgyface
Copy link
Author

morgyface commented Mar 31, 2018

ID of first page using a specific template

I'm using this where my contact page uses a specific template. No other pages will be using the same template. I can then grab fields from that page simply by identifying the template it uses, this means the page title or ID can vary without there being an issue.

To use this, add it to your functions.php page.

Then use it where you need it like so:

$contact_page_id = page_id_from_template( 'contact-page.php' );
echo '<p>ID of page using the contact template is:' . $contact_page_id . '</p>';

if you want a function that goes the whole way and returns a URL, try this one.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment