Get page IDs based on which template they are using?

I have a situation where I need to provide a dropdown of pages in a widget, based on whether they are using a specific template. In other words, for all pages using template ‘Foo’, get the post ID.

I have coded the rest of the widget, but I’m using an input field for entering a page ID (which can get messy with non-technical users, having to figure out the page ID to use) – I would much rather provide a select box with the page title of the pages using the specific template.

Read More

I have tried getting the WP_Query object with this:

$the_query = new WP_Query(array(
    'meta_key' => '_wp_page_template',
    'meta_value' => 'templates/_partner.php'
));

The meta value is corrent (corresponds to 2 entries in the database), but I don’t get any results on the widget page. The select box is empty.

Can you not call WP_Query from a widget, or do I need to look elsewhere for this solution?

UPDATE
I checked the $the_query->request for the SQL that runs this, and it returns no rows. It turns out that I was missing the ‘post_type’ => ‘page’ in the query.

Related posts

Leave a Reply

3 comments

  1. You can use wp_dropdown_pages() to directly create a drop-down list of the pages you would like to display:

    $args = array(
        'name' => '_partner_page', // "name" attr of the <select> element
        'id' => 'partner-page', // id attr of the <select> element
        'hierarchical' => 1, // set to 0 for flat display
        'echo' => 1, // set to 0 to return
        'selected' => $post->ID, // ID of the option with "selected" attr, set to 0 to disable
        'meta_key' => '_wp_page_template',
        'meta_value' => 'templates/_partner.php'
    );
    wp_dropdown_pages($args);
    

    There are alot of agruments you can pass to wp_dropdown_pages(). Besides the ones on the codex page of this function, you also can pass any argument listed on get_pages() function, as wp_dropdown_pages() uses get_pages() to retrieve the list of pages that will be displayed as dropdown list.

  2. $query= new WP_Query(array(
        'post_type'  => 'page',  /* overrides default 'post' */
        'meta_key'   => '_wp_page_template',
        'meta_value' => 'page-templates/{template name}.php'
    ));
    

    This worked for me because my custom theme used page-templates folder.