Thursday, 20 February 2014

Excluding a certain category when using Wordpress's have_posts function

Using Wordpress's 'have_posts' function is pretty darn cool.  It fetches a list of your most recent post; the number of which is set in
Admin -> Settings -> Reading -> 'Blog pages show at most'

This array can then be iterated through thus

  while (have_posts()) {   // WP function that gets post
                    the_post( ); 

what I wanted to do is eliminate a certain category from being returned in the have_posts

and thought I could get away with something like

foreach(get_the_category() as $category) {
$cat_ID = $category->cat_ID;
if($cat_ID == '81' || $cat_ID == '82') {} else {

in the while statement to solve this.  However this would change the number of posts I was displaying.  Something I didn't want.    The solution was to use query_posts  which adds to the have posts function.  It's not ideal in all situations but fine for what I was doing.

query_posts( 'cat=83&cat=84' );
            if (have_posts()) {

Wordpress Development Cornwall

No comments: