Forums

[resolved] Querying posts from one category and exclude another (3 posts)

  1. JiRaffe
    Member
    Posted 2 weeks ago #

    Hi all

    I've been setting up a portfolio theme and I've set it up so that the user can categorise projects in both the 'featured' and the 'portfolio' categories. The problem I'm having is that in the sidebar I want to display the 3 latest portfolio posts, but exclude the featured projects (as these are already listed above it). The following code works fine for me, with the exception that if a 'featured' project is one of the three most recent 'portfolio' projects then it only lists 2 posts instead of the desired 3. here's the code...

    <?php
    			query_posts('showposts=3&category_name=portfolio');
    			$ids = array();
    			while (have_posts()) : the_post();
    				if (in_category('9')) continue;
    				$ids[] = get_the_ID();
    				$portfolio_thumb_image_url = get_post_meta($post->ID, "portfolio_thumb_image_url", true);
    				?>
    
    				<li><a href="<?php the_permalink() ?>" rel="bookmark"><img src="<?php echo $portfolio_thumb_image_url ?>" /><span><?php the_title(); ?></span></a></li>
    
    				<?php
    
    			endwhile;
    			?>

    So does anyone know a work-around? Perhaps is there a way to subtract from the loop count or something? Any help would be great!

    Thanks!

  2. stvwlf
    Member
    Posted 2 weeks ago #

    The problem with query_posts, if I recall, is you can include category x and exclude category y, but if a post in category y is also in category x, it gets included.

    Here's a solution. Its a slight kludge but it gets the job done. The gist is query for more posts than are needed, skip the ones in the unwanted category, and when more than 3 wanted ones have been processed, skip over the rest. I am querying for 6 posts here:

    <?php	query_posts('showposts=6&category_name=portfolio');
    $ids = array();
    $i = 0;
    while (have_posts()) : the_post();
    	if ($i > 3) continue;
    	if (in_category('9')) continue;
    	$i++;
    	$ids[] = get_the_ID();
    	$portfolio_thumb_image_url = get_post_meta($post->ID, "portfolio_thumb_image_url", true); ?>
    	<li><a href="<?php the_permalink() ?>" rel="bookmark"><img src="<?php echo $portfolio_thumb_image_url ?>" /><span><?php the_title(); ?></span></a></li>
    <?php endwhile; ?>
  3. JiRaffe
    Member
    Posted 2 weeks ago #

    That's a neat little fix! Thanks for that stvwlf, worked likea charm! :)

Reply

You must log in to post.

About this Topic