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.

3 s
3

WP_Query goes only through posts by default.

Try adding page as your post type:

$the_query = new WP_Query(array(
    'post_type'  => 'page',  /* overrides default 'post' */
    'meta_key'   => '_wp_page_template',
    'meta_value' => 'templates/_partner.php'
));

See: WP_Query – Type Parameters

Leave a Reply

Your email address will not be published. Required fields are marked *