Post Template Query with WP_Query?

I've seen this solution for querying pages based off of template type: Page template query with WP_Query

I'm having trouble getting it to work with posts, that are using a "Single Post Template:" rather than a "Template Name:" definition.

Here is my code:

 // query
$the_query = new WP_Query( array(
  'post_type' = 'post',
  'posts_per_page'  = -1,
  'meta_query' = array(
     array(
     'key' = '_wp_page_template', 
     'value' = 'single-current.php'
     )
   )
));

Is there a different 'key' I should be using?

Something like '_wp_post_template'

Thanks.

Topic single wp-query Wordpress

Category Web


Thanks all for the responses. It turns out the site in question was actually using the "single post template" plugin, and the templates were defined like this:

Single Post Template: Fullwidth
Description: Like single post but without sidebar.

I think this was in place for a while. I updated the templates to this:

Template Name: Fullwidth
Template Post Type: post
Description: Like single post but without sidebar.

I got rid of the extra plugin, reassigned the posts, and now my original query is working.


I recently ran into a situation where I needed to query posts in this same way. Post use the same _wp_page_template meta to store the template as pages.

Here are some arguments that should work:

$args = array(
    'post_type' => 'post',
    'meta_key' => '_wp_page_template',
    'meta_value' => 'templatename.php'
);

If your template is within a folder in your theme, the path will need to be included as well:

$args = array(
    'post_type' => 'post',
    'meta_key' => '_wp_page_template',
    'meta_value' => 'templates/templatename.php'
);

You can also query for posts that use the default template:

$args = array(
    'post_type' => 'post',
    'meta_key' => '_wp_page_template',
    'meta_value' => 'default'
);

If you are still stuck, one possible alternative is to get all Post ID's by the custom post type. You could try something like this:

$the_query = new WP_Query( array(
  'post_type' => 'my-custom-post',
  'posts_per_page'  => -1,
   )
));
while ( $the_query->have_posts() ) : $the_query->the_post();
    the_ID();
endwhile;

It would require you creating a custom post type, and associating posts to it.

There are ways you can associate page templates to posts, but as far as how WP_Query would work from that point with that process, I still have to learn :)

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.