Query Posts


query_posts() is the easiest, but not preferred or most efficient, way to alter the default query that WordPress uses to display posts. Use query_posts() to display different posts than those that would normally show up at a specific URL. (The preferred way is hooking into ‘pre get posts’ and altering the main query that way using is main query)

For example, on the homepage, you would normally see the latest 10 posts. If you want to show only 5 posts (and don’t care about pagination), you can use query_posts() like so: query_posts( 'posts_per_page=5' );

Examples:

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

Exclude Categories From Your Home Page

Placing this code in index.php file will cause the home page to display posts from all categories except category ID 3.

<?php
if ( is_home() ) {
	query_posts( 'cat=-3' );
}
?>

You can also add some more categories to the exclude-list (tested with WP 3.3.1):

<?php
if ( is_home() ) {
	query_posts( 'cat=-1,-2,-3' );
}
?>

Retrieve a Particular Post

To retrieve a particular post, you could use the following:

query_posts( 'p=5' );

Note: If the particular post is an attachment, you have to use attachment_id instead of p:

query_posts( 'attachment_id=5' );

If you want to use the Read More functionality with this query, you will need to set the global $more variable to 0.

<?php
// retrieve one post with an ID of 5
query_posts( 'p=5' );

// set $more to 0 in order to only get the first part of the post
global $more;
$more = 0;

// the Loop
while (have_posts()) : the_post();
	the_content( 'Read the full post »' );
endwhile;
?>
Advertisements