0

I have a simple loop that outputs the content of posts and then adds some navigation links at the bottom. Wordpress is set to only show 5 posts at a time.

<?php while(have_posts()) : the_post(); ?>
    <div class="post">
        <?php the_content(); ?>
    </div>
<?php endwhile; ?>
<div class="navigation"><?php posts_nav_link(" - ", "&laquo; Newer Posts", "Older Posts &raquo;"); ?></div>
<?php wp_reset_postdata(); ?>

My client asked me to modify this and exclude a category from the list. I tried adding

<?php query_posts('cat=4'); ?>

before the loop. This does filter out the desired posts, but it has messed up the navigation. Now when I press the "Older posts" link at the bottom of the page, I don't get posts 6-10. Instead, posts 1-5 just repeat. The url however does change to say /news/page/2. If I press the "Older posts" link again, I still get posts 1-5 and the url changes to /news/page/3. I have about 22 posts in total, so I can repeat this process 4 times. Wordpress removes the "Older posts" link at the bottom after 4 clicks so it does understand how many posts I have in total (and it adjusts the url accordingly each time). It just doesn't output the correct posts.

I also tried creating a brand new query

<?php $query = new WP_Query(  'cat=4'); ?>
<?php while($query->have_posts()) : $query->the_post(); ?>
    <div class="post">
        <?php the_content(); ?>
    </div>
<?php endwhile; ?>
<div class="navigation"><?php posts_nav_link(" - ", "&laquo; Newer Posts", "Older Posts &raquo;"); ?></div>
<?php wp_reset_postdata(); ?>

That didn't work either. Can someone point me the right direction?

  • 'cat=-4' why there is a minus sign (-) before 4? – Mayeenul Islam Oct 18 '14 at 18:10
  • 1
    That is what excludes the category. 'cat=4' would only show posts from category 4. 'cat=-4" shows everything EXCEPT category 4. – CodeSmith Oct 18 '14 at 18:43
  • Your question title is "Show Posts from Single Category Not Working" and you are excluding a single category but showing all others seems self-contradictory to me. :( – Mayeenul Islam Oct 19 '14 at 4:03
  • Good catch. I changed the example to get rid of the minus sign. – CodeSmith Oct 20 '14 at 2:29
  • On which page/template is that – Pieter Goosen Oct 20 '14 at 4:22
2

Take a look the section called Preserving Existing Query Parameters on http://codex.wordpress.org/Function_Reference/query_posts

Try merging in the existing query parameters; they might be getting overridden. Instead of:

<?php query_posts('cat=4'); ?>

try

global $query_string;
query_posts( $query_string . '&cat=4' );
  • query_posts may work for you now but this is not the recommended way. Read first paragraph in this page. – Nilambar Oct 27 '14 at 3:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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