How to Use “query_posts” in wordpress
Description:
How to hide posts from your Home Page? How to show post from specific category in your sidebar? Unique answer is Using the query_posts function.
This function is a native Wp Function, and allow the bloggers to query post directly from Wp Db. You can use query posts function to call post by different parameters.
You can call posts by tags, by type, by category or by date (day, month and year); you can call single post by id,.
The Code:
query_posts Rules:
To use query posts you have to respect 2 rules:
- You have to use query posts before “The Loop” starts
- You need to post The Loop every time you use query posts
Be carefull, every time you use query_posts wp make a SQL call, this mean that your blog’s speed can be compromised.
Simple Query:
Supposing you want to call the firsts 5 posts from category who have id 8 you need to replace your loop:
<?php query_posts( "cat=8&posts_per_page=-5" ); if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> //now the single Tag <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> //now the content <?php the_content(); ?> //Finally close the loop <?php endwhile; ?> <?php endif; ?>
To Hide category with the ID = 8 from home just add
query_posts("cat=-8");
before the Loop Start
Array:
And Now a simple Array:
<?php $wpc_post_array = array( 'cat' => 8, 'posts_per_page' => 10, 'monthnum' => $2011, //replace with $current_month set the current month 'order' => 'ASC' // or DESC ); query_posts( $wpc_post_array ); //The Loop goes here //and now all the post tag
For further reference Query Posts and The Loop @ Wp Codex


