About design and nearby

How to Show or Exclude Posts from a Single Category only for WordPress

Posted: April 17th, 2014 | Author: | Filed under: Development, Tips and Tricks | Tags: , , | No Comments »

If you have ever wanted to display or hide posts from a specific category only, then it’s pretty easy to do – if you know how.

So you have a WordPress blog with a list of categories. You have specific template (say, the footer section) which is applied to all categories exept “Press Release”. And you need to exclude the posts with certain category (“Press Release”) from this template.

A Small Intro

WordPress has the ‘query_posts’ codex – to alter the main query that WordPress uses to display posts.
If you want to show posts from one specific category (“Press Release”), the code is:

  1. <?php query_posts('category_name=Press Release'); ?>


To show posts from some number of categories, you just list those categories – as many as you need. You can use Category Title (or Category ID) for that:

  1. <?php query_posts('category_name=Press Release, Another Category'); ?>

To control the number of posts (3 for our case) you want to appear use ‘showposts’ or ‘posts_per_page’ with ‘&’:

  1. <?php query_posts('category_name=Press Release&showposts=3'); ?>

or

  1. <?php query_posts('category_name=Press Release&posts_per_page=3'); ?>

The Solution:

To exclude a WordPress category by name from posts you should simply add ‘-‘ before the name of this category:

  1. query_posts( 'category_name=-Press Release' );

but, to be honest, that didn’t work for me. I created custom function, the solution is below:

  1. <?php
  2.  $exclude = get_cat_ID('Press Release'); //my custom solution
  3.  $q = 'cat=-'.$exclude;
  4.  query_posts($q);    
  5.  
  6.  $latest = new WP_Query( 'cat=' .$q. '&posts_per_page=2' ); // exclude posts from Category 'Press Release', show max 2 posts
  7.  if( $latest->have_posts() ) : ?>
  8.     <ul>
  9.   <?php while( $latest->have_posts() ) : $latest->the_post(); ?>
  10.             <li>      
  11.    <?php if ( has_post_thumbnail()) : ?>
  12.     <span>
  13.      <?php the_post_thumbnail(array(80,80)); ?> // show thumbnail if post has the thumbnail
  14.     </span>              
  15.    <?php endif; ?>            
  16.             <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
  17.             </li>      
  18.   <?php endwhile; ?>
  19.     </ul>  
  20. <?php endif; wp_reset_postdata(); ?>

You could be interested to read related post: How to Display Latest Blog Posts

Share Button

Check Related Posts:


Leave a Reply


  • nine − 7 =

Looking for a Freelance UX & UI designer for your project? I’m ready to jump onboard!

Let's discuss your project now