Using WP_Query to Fetch Posts in WordPress

I was just putting together a WordPress widget for a client and I came across a small road block. I was using <?php query_post(); ?> to set the loop to act the way I needed it to but when the widget loaded up in the left sidebar, it caused some issues when going to a category page. The problem was the query I initialized in the sidebar was carrying over to the main section. I couldn’t figure out what to do until I stumbled up the wp_query function. It works in a similar way to query_post but you need to do a few minor things to get it to work properly.
query('showposts=5&cat=3');
while ($featuredPosts->have_posts()) : $featuredPosts->the_post(); ?>

By
First you need to setup the query.
$featuredPosts = new WP_Query();
$featuredPosts->query('showposts=5&cat=3');
Then you need to setup the loop.
while ($featuredPosts->have_posts()) : $featuredPosts->the_post(); ?>
     (stuff goes here)

So in the end it looks something like this.
query('showposts=5&cat=3');
while ($featuredPosts->have_posts()) : $featuredPosts->the_post(); ?>

By
What this will do is get 5 posts from category 3 and list them, without interfering with other loops or queries on your site.
Search

Popular Posts

Small Biz Website Tips Newsletter

Stay up to date with the latest marketing, sales, and service tips and news.

Small Biz Website Tips Newsletter

Stay up to date with the latest marketing, sales, and service tips and news.