Webtips

Retriving WordPress Posts

techrounder-default

WordPress can retrieve a different set of posts with the query_posts() function. For example, this query limits the page to five posts:

query_posts( 'posts_per_page=5' );

WordPress has already run its main database query before it loads a template. Calling query_posts() replaces that query and runs another one. The extra query may be acceptable on a small site, but it can add unnecessary work on a large or busy site.

The request, parse_query, and pre_get_posts filters can change the main query before WordPress runs it. When you must use query_posts(), reset the query afterward:

// The Query
query_posts( $args );
// The Loop
while ( have_posts() ) : the_post();
the_title();
endwhile;
// Reset Query
wp_reset_query();

Combine query parameters with an ampersand:

query_posts( 'cat=3&year=2004' );

This example requests posts from category 13 for the current month on the home page:

if ( is_home() ) {
query_posts( $query_string . '&cat=13&monthnum=' . date( 'n', current_time( 'timestamp' ) ) );
}

The following array requests posts that belong to categories 1 and 3, limits the result to two posts, and sorts titles in descending order:

query_posts( array( 'category__and' => array(1,3), 'posts_per_page' => 2, 'orderby' => 'title', 'order' => 'DESC' ) );

This query returns posts from category 1 with the tag apples:

query_posts( 'cat=1&tag=apples' );

You can join several tags with a plus sign:
query_posts( 'cat=1&tag=apples+apples' );

For new template work, I recommend changing the main query with pre_get_posts when possible and reserving query_posts() for legacy code that you cannot replace yet.

Leave a Comment