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.

Share this:

Email
Facebook
Twitter
Pinterest
Pocket

Premium Themes for WordPress

Looking for an easy-to-use Premium Theme for WordPress? Check out Themes by bavotasan.com and have your site up and running in no time.

Use this WordPress website builder to build powerful websites in no time for your or your clients.

WordPress Hosting

WP Engine – designed from the ground-up to support and enhance the workflow of web designers.

Bluehost – providing quality web hosting solutions since 1996.

About the author

Picture of Luke Perrie

Luke Perrie