There are legitimate scenarios for using query_posts($query)
, for example:
You want to display a list of posts or custom-post-type posts on a page (using a page template)
You want to make pagination of those posts work
Now why would you want to display it on a page instead of using an archive template?
It\'s more intuitive for an administrator (your customer?) - they can see the page in the \'Pages\'
It\'s better for adding it to menus (without the page, they\'d have to add the url directly)
If you want to display additional content (text, post thumbnail, or any custom meta content) on the template, you can easily get it from the page (and it all makes more sense for the customer too). See if you used an archive template, you\'d either need to hardcode the additional content or use for example theme/plugin options (which makes it less intuitive for the customer)
Here\'s a simplified example code (which would be on your page template - e.g. page-page-of-posts.php):
/**
* Template Name: Page of Posts
*/
while(have_posts()) { // original main loop - page content
the_post();
the_title(); // title of the page
the_content(); // content of the page
// etc...
}
// now we display list of our custom-post-type posts
// first obtain pagination parametres
$paged = 1;
if(get_query_var(\'paged\')) {
$paged = get_query_var(\'paged\');
} elseif(get_query_var(\'page\')) {
$paged = get_query_var(\'page\');
}
// query posts and replace the main query (page) with this one (so the pagination works)
query_posts(array(\'post_type\' => \'my_post_type\', \'post_status\' => \'publish\', \'paged\' => $paged));
// pagination
next_posts_link();
previous_posts_link();
// loop
while(have_posts()) {
the_post();
the_title(); // your custom-post-type post\'s title
the_content(); // // your custom-post-type post\'s content
}
wp_reset_query(); // sets the main query (global $wp_query) to the original page query (it obtains it from global $wp_the_query variable) and resets the post data
// So, now we can display the page-related content again (if we wish so)
while(have_posts()) { // original main loop - page content
the_post();
the_title(); // title of the page
the_content(); // content of the page
// etc...
}
Now, to be perfectly clear, we could avoid using query_posts()
here too and use WP_Query
instead - like so:
// ...
global $wp_query;
$wp_query = new WP_Query(array(\'your query vars here\')); // sets the new custom query as a main query
// your custom-post-type loop here
wp_reset_query();
// ...
But, why would we do that when we have such a nice little function available for it?