Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

How can I only show items from a certain category (category 51)?

Here's my loop below that I need to incorporate the code into.

<div class="news-content-inner">
  <?php $portfolioloop = new WP_Query( array( 'paged' => get_query_var('paged'), 'post_type' => 'news', 'posts_per_page' => 4 ) ); ?>
  <?php while ( $portfolioloop->have_posts() ) : $portfolioloop->the_post(); ?>
  <div class="news-item" onClick="location.href='<?php echo the_permalink(); ?>'">
    <h2><a style="color:#F45B11!IMPORTANT;" href="<?php echo the_permalink(); ?>"><?php echo the_time('d.m.Y'); ?> / <?php echo the_title(); ?></a></h2>
    <p class="news-page">
      <?php if (get_field('description') != "") { ?>
      <?php echo the_field('description'); ?>
        <?php } else { 
        $newscontent = get_the_content();
        $newscontent_str = strip_tags($newscontent, '');
        echo substr($newscontent_str,0,250) . "…";
        } ?>
    </p>
  </div>
  <?php endwhile; // end of the loop. ?>
  <p class="news-page" style="font-size:12px!IMPORTANT;"><?php echo wp_count_posts('news')->publish; ?> opportunities</p>
    <?php if (function_exists('wp_pagenavi')) {
    wp_pagenavi( array( 'query' => $portfolioloop ) ); } ?>
</div>
share|improve this question

1 Answer 1

up vote 2 down vote accepted

You need to modify your WP_Query loop. Add a tax_query argument to filter the category you want.

$portfolioloop = new WP_Query(array(
    'paged'          => get_query_var('paged'),
    'post_type'      => 'news',
    'posts_per_page' => 4,
    'tax_query'      => array(
        // Note: tax_query expects an array of arrays!
        array(
            'taxonomy' => 'portfolio', // my guess
            'field'    => 'id',
            'terms'    => 51,
        ),
    ),
));

http://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters

share|improve this answer
    
Thanks, that worked great. The only thing that's not quite right is the wp_count_posts bit at the bottom. It's counted the total number of posts instead of the number of posts that are within the category. How can I change that? –  Rob Apr 27 '12 at 9:12
1  
@Rob: try $portfolioloop->post_count –  Geert Apr 27 '12 at 9:17
    
Brilliant, thanks. –  Rob Apr 27 '12 at 9:18
1  
You're welcome. To get the total number of posts (regardless of pagination) use $portfolioloop->found_posts. –  Geert Apr 27 '12 at 9:21
    
Ok great, didn't know that. –  Rob Apr 27 '12 at 9:21

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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