Created
February 21, 2013 01:42
-
-
Save Vheissu/5001244 to your computer and use it in GitHub Desktop.
A function that allows you to query pages by their page_template in Wordpress.
This file contains 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 | |
function get_page_by_template($template_name, $single_key = FALSE, $return = true) { | |
$args = array( | |
'post_type' => 'page', | |
'meta_query' => array( | |
array( | |
'key' => '_wp_page_template', | |
'value' => $template_name | |
) | |
) | |
); | |
// Query for our page by template name | |
$contact_query = new WP_Query($args); | |
// We should only ever have one, but if the template is usable on multiple pages | |
// then this is good to have. | |
if ( $contact_query->have_posts() ) { | |
// This is where we'll store our info | |
$info_arr = array(); | |
// While we have pages | |
while ( $contact_query->have_posts() ) { | |
$contact_query->the_post(); | |
$info_arr[] = array( | |
'ID' => get_the_ID(), | |
'title' => get_the_title(), | |
'url' => get_permalink() | |
); | |
} | |
wp_reset_query(); | |
// If we have an array with page data | |
if ( !empty($info_arr) ) { | |
// If only one page in our array, simplify the array | |
if ( count($info_arr) == 1 ) { | |
// Simplified array | |
$info_arr = $info_arr[0]; | |
} | |
// If we are returning the array, then return it | |
if ($return === TRUE) { | |
if ($single_key === FALSE) { | |
return $info_arr; | |
} else { | |
if ( isset($info_arr[$single_key]) ) { | |
return $info_arr[$single_key]; | |
} | |
} | |
} | |
// If we have a single key and want to echo | |
if ($single_key !== FALSE && $return === FALSE) { | |
// Check our single key exists | |
if (isset($info_arr[$single_key])) { | |
echo $info_arr[$single_key]; | |
} else { | |
return FALSE; | |
} | |
} | |
} else { | |
// Array is empty, give it and return FALSE | |
return FALSE; | |
} | |
} | |
} | |
$stuff = get_page_by_template('page-template-file-name.php'); | |
if ($stuff) { | |
print_r($stuff); | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment