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

6 thoughts on “Query Posts

  1. Fantastic site. A lot of useful information here. I’m sending it to a few friends ans additionally sharing in delicious. And of course, thank you on your effort!

  2. Hi there! Someone in my Myspace group shared this website with us so I came to check it out. I’m definitely enjoying the information. I’m book-marking and will be tweeting this to my followers! Fantastic blog and outstanding design.

  3. Thanks for sharing superb informations. Your site is so cool. I am impressed by the details that you’ve on this web site. It reveals how nicely you understand this subject. Bookmarked this web page, will come back for more articles. You, my pal, ROCK! I found simply the info I already searched all over the place and simply couldn’t come across. What a perfect site.

Comments are closed.