Retriving WordPress posts

WordPress posts can be retrived by using the function query_posts(). By using this function different posts can be displayed on different pages even on the basis of different category.

For example, on the homepage, you may see the latest 10 posts. If you want to show only 5 posts , it can be done using query_posts()

query_posts( ‘posts_per_page=5’ );

If you use query_posts within a template page, WordPress will have already executed the database query and retrieved the records by the time it gets to your template page (that’s how it knew which template page to serve up!). So when you over-ride the default query with query_posts(), you’re essentially throwing away the default query and its results and re-executing another query against the database.

This is not necessarily a problem, especially if you’re dealing with a smaller blog-based site. Developers of large sites with big databases and heavy visitor traffic may wish to consider alternatives, such as modifying the default request directly (before it’s called). The request filter can be used to achieve exactly this.

The ‘parse_query’ and the ‘pre_get_posts’ filters are also available to modify the internal $query object that is used to generate the SQL to query the database.

 

// The Query
query_posts( $args );

// The Loop
while ( have_posts() ) : the_post();
echo ‘

  • ‘;
    the_title();
    echo ‘

 

‘;
endwhile;

// Reset Query
wp_reset_query();

?>

Here parameters are combined with an ampersand (&), like so:

query_posts( ‘cat=3&year=2004’ );

Posts for category 13, for the current month on the main page:

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

this combination will return posts belong to both Category 1 AND 3, showing just two posts, in descending order by the title:

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

The following returns all posts that belong to category 1 and are tagged “apples”

query_posts( ‘cat=1&tag=apples’ );

You can search for several tags using +

query_posts( ‘cat=1&tag=apples+apples’ );

Sharing is caring!

Leave a Comment