Skip to content

@Vheissu /functions.php
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
A function that allows you to query pages by their page_template in Wordpress.
<?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
Something went wrong with that request. Please try again.