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.
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.
WP_Query goes only through posts by default.
Try adding
page
as your post type:See: WP_Query – Type Parameters
You can use
wp_dropdown_pages()
to directly create a drop-down list of the pages you would like to display: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 onget_pages()
function, aswp_dropdown_pages()
usesget_pages()
to retrieve the list of pages that will be displayed as dropdown list.This worked for me because my custom theme used page-templates folder.