0

I'm working on a theme homepage and would like to include an excerpt from the latest post in a specific category. In this case, the category slug is "gear". I've tried a couple options with WP_Query but am unable to get it to return only one post.

Here's my current code:

<?php $latest1 = new WP_Query();
$args=array('category_name=gear','posts_per_page=1');
$latest1->query($args);
while ($latest1->have_posts()) : $latest1->the_post(); ?>
<h1 class="home-article-title"><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h1>
<div class="storycontent">
<?php the_excerpt(); ?>
</div>
<?php endwhile; wp_reset_query(); ?>

There are currently two posts in the "gear" category, and both are being returned. I must be misunderstanding the posts_per_page option.

If there's a better way to do this than WP_Query (making this call three times on the page, once for each category), I'm open to that as well.

2
  • Did you check for the existence of a filter on 'pre_get_posts' which might override your args settings?
    – marfarma
    Aug 28, 2012 at 20:07
  • @marfarma I'm building this theme based on _s and haven't added any filters on pre_get_posts.
    – ahockley
    Aug 28, 2012 at 20:12

1 Answer 1

1

Try this:

$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$wp_query = new WP_Query("category_name=$catName&paged=$paged&posts_per_page=1");

Basically, add the paged variable to the args -- since it's your home page, you could hard code it to equal 1, of course.

1
  • Thanks, I tweaked the code such that 'posts_per_page' => 1, 'paged' => 1 and things are now working.
    – ahockley
    Aug 29, 2012 at 0:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.