Support » Everything else WordPress » Display posts from a single category

  • Didn’t know where to post this but I wanted to lend some people a hand. I have just spent a while researching how to show two loops on the main page. I wanted to show the News category in it’s own style at the top of my page. So here’s how I did it –

    This page gave me a clue on how to do it – Query Posts

    Using this piece of code – <?php query_posts('cat=7'); ?>
    before my loop started and after the loop was done I used this code – <?php query_posts(); ?> This piece of code resets the query to allow the second loop to show it’s posts.

    So basically my loop looks like this –

    <!-- Start the Loop. -->
    <?php query_posts('cat=7'); ?>
    <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
    <!-- The following tests if the current post is in category 3. -->
    <!-- If it is, the div box is given the CSS class "post-cat-three". -->
    <!-- Otherwise, the div box will be given the CSS class "post". -->
    	<?php if ( in_category('3') ) { ?>
    		<div class="post-cat-three">
    	<?php } else { ?>
    	<div class="postcontainernews">
    		<?php } ?>
    		<!-- Display the Title as a link to the Post's permalink. -->
    		<div class="posttitlenews"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></div>
    		<span class="edit"><?php edit_post_link(); ?></span>
    	</div> <!-- closes the first div box -->
    	<!-- Stop The Loop (but note the "else:" - see next line). -->
    	<?php endwhile; else: ?>
    	<!-- The very first "if" tested to see if there were any Posts to -->
    	<!-- display.  This "else" part tells what do if there weren't any. -->
    	<p>Sorry, no posts matched your criteria.</p>
    <!-- REALLY stop The Loop. -->
    <?php endif; ?>
    <?php query_posts(); ?>

    Only thing left was to exclude the category in the first loop from the second loop. I did it with this code – <?php if ( in_category('7') && is_home() ) continue; ?> I placed this code right after this code in the second loop – <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

    Now I got the effect I needed. I really wanted to share the end result because it seems there are some people who need help with achieving this effect. Hope it helps someone out there.

Viewing 1 replies (of 1 total)
  • Thank you for this post. I’m not a php programmer and haven’t found it particularly easy to find this solution.

    Thanks again

Viewing 1 replies (of 1 total)
  • The topic ‘Display posts from a single category’ is closed to new replies.