Get page by template?

I’m in a complicated situation. I’ll try to explain it as easy as possible.

Imagine the following pages:

  • Page 1
  • Page 2
    • Subpage 1
    • Subpage 2
    • Subpage 3

Each subpage of page 2 lists posts from a custom post type with a specific taxonomy. Let’s call the post type Objects, and the taxonomy just Categories, to keep it simple.

To list the different posts from the different Categories, i have three different page templates for the subpages: subpage-1-templ.php, subpage-2-templ.php and subpage-3-templ.php. Each one of these templates lists the posts from a specific Category for the post type (Objects). It’s hardcoded.

So far all good, it works as expected. It’s a little ugly to have to hardcode it but i don’t know of any other way, so this’ll have to work for now. (I’d prefer to ditch wordpress alltogether but that’s another story)

All of those subpages lists the siblings in a sub menu. So, if you’re on subpage 2 it will show subpage1, 2 and 3 (but subpage 2 has a current class on it). Works good.

Now to the actual problem; when you click one of the posts listed in a subpage, you get to a page which displays more info for the post, as expected. The problem is i want to show the submenu for page 2 in there (so, subpage1, 2 and 3). I don’t know how to do that without hardcoding it.

Perhaps, and i don’t know if this will work, but maybe i can find a page by it’s template. I can create a template for page 2 (not for it’s children, the actual parent page) called objects-template.php and then on a post, i can grab the page that uses the template, then get all it’s children, and then just simply list them up. I just don’t know how to get a page by it’s template, if that’s even possible (Preferably by the template file name, but the template name works too).

Any suggestions?

Edit

    // Query looks fine right?
    $query = new WP_Query(array(
        'meta_key' => '_wp_page_template',
        'meta_value' => 'objects-parent-page-template.php'
    ));
    // Dump the id (also tried just getting the object with get_queried_object(), still get null)
    echo '<pre>'; var_dump($query->get_queried_object_id()); die();

1 Answer
1

The page template’s filename is stored as a post meta with key ‘_wp_page_template’, so basically you can use get_post_meta($post_id, '_wp_page_template', true); to get the template filename for the page with ID $post_id.

You can also do the reverse (i.e. getting id from page template filename) using Custom Field Parameters in WP_Query or other wordpress functions.

Also there is a conditional function is_page_template which checks if the current page’s template is the one specified in parameter

These will probably solve your problem & maybe help to get rid of the hardcoded stuff.

Leave a Comment