Get page ID by template

A useful functionality in WordPress is the use of page templates. This allows you to create custom made template that you specifically link to a specific page.

Sometimes it is useful to check which pages are attached to this template. For example, if you want an overview of exactly those pages or if you want to load specific hook when this page is loaded.

To find the ID of this page on the basis of the page template, I use the following function:

/**
 * Returns page id by template file name
 *
 * @param string $template name of template file including .php
 */
function get_page_id_by_template( $template ) {
    $args = [
        'post_type'  => 'page',
        'fields'     => 'ids',
        'nopaging'   => true,
        'meta_key'   => '_wp_page_template',
        'meta_value' => $template
    ];
    $pages = get_posts( $args );
    return $pages;
}

I first retrieve all the post id’s with the post type “page”. Then I filter them by using the meta query functionality to find only posts that have meta data attached with a meta key: “_wp_page_template” and meta value: “page-special.php” (the name of the page template file).

Leave a reply

Feel free to ask questions or make comments.

Comments

    No comments yet..