Last active
August 27, 2019 10:32
-
-
Save morgyface/c088e55381133388c0e150060c7711ec to your computer and use it in GitHub Desktop.
WordPress | Get the ID of the first page using a specific template
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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; | |
| } | |
| } | |
| ?> |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.phppage.Then use it where you need it like so:
if you want a function that goes the whole way and returns a URL, try this one.