A Custom WordPress Function for Querying Pages by Page Template

Sometimes in WordPress when you want to query a particular page but don’t know it’s ID and know better than to rely on it’s title there is no way to really query it. For example if you had a contact page that used a custom template called, “contact-page-template.php” there is no internal function that does this for you.

WordPress stores the page template into a private custom field on each page that has a custom template assigned. Using meta queries, we can query pages by this custom value. The following function will allow you to query a page by it’s template and either return or echo an array of contents as well as support for a single key (you only want the title or url for example).

 '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);
}

?>