Using WP_Query to Fetch Posts in WordPress
by Bandicoot Marketing on | Posted in Tutorials | 25 comments
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.
<?php $featuredPosts = new WP_Query(); $featuredPosts->query('showposts=5&cat=3'); while ($featuredPosts->have_posts()) : $featuredPosts->the_post(); ?> <h1><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h1> <div class="meta"> By <?php the_author() ?> </div> <div class="storycontent"> <?php the_excerpt(); ?> </div> <?php endwhile; ?>
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) <?php endwhile; ?>
So in the end it looks something like this.
<?php $featuredPosts = new WP_Query(); $featuredPosts->query('showposts=5&cat=3'); while ($featuredPosts->have_posts()) : $featuredPosts->the_post(); ?> <h1><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h1> <div class="meta"> By <?php the_author() ?> </div> <div class="storycontent"> <?php the_excerpt(); ?> </div> <?php endwhile; ?>
What this will do is get 5 posts from category 3 and list them, without interfering with other loops or queries on your site.
25 comments for “Using WP_Query to Fetch Posts in WordPress”