public
Created

A function that allows you to query pages by their page_template in Wordpress.

  • Download Gist
functions.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
<?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);
}
 
?>

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.