Forums

pulling recent posts from a random category or none if category is empty (5 posts)

  1. PaulWarren
    Member
    Posted 2 weeks ago #

    In my sidebar I am using this code to display 8 recent posts from whatever category is being viewed: `<?php $post_cats=wp_get_post_categories($post->ID);?>
    <?php
    $args=array(
    'showposts'=>8,
    'cat'=>$post_cats[0]
    );
    $postslist = get_posts($args);
    if ($postslist) {
    foreach ($postslist as $mypost) :
    ?>

  2. ID); ?>"><?php echo $mypost->post_title; ?>
  3. <?php endforeach;
    }
    }
    ?>`

    When the category is empty, There should be nothing displayed - instead, I am getting posts from a different category. There must be an easy way to fix this...

  • richarduk
    Member
    Posted 2 weeks ago #

    First question: are you absolutely sure that the other posts aren't also in this category? i.e. you don't have posts that are in several categories?

  • MichaelH
    moderator
    Posted 2 weeks ago #

    Doesn't every post need to have at least one category? That code looks to return the first category on the post. Put an <?php echo 'post cat '. $post_cats; ?> after $post_cats=wp_get_post_categories($post->ID);?> to see what category it is using.

  • PaulWarren
    Member
    Posted 2 weeks ago #

    Michael -

    When I add the bit of php you mentioned I get "post cat Array" instead of the category.

    Yes, Richard - I am sure that they are not in multiple categories. This really isn't the issue anyway. The issue only appears when there are NO posts in the given category.

    Paul

  • richarduk
    Member
    Posted 2 weeks ago #

    Okay, obvious solution: make sure every category has a post. Put it a million light years into the future, if necessary, if you haven't written any posts for that category yet.

    Next solution, rewrite your code. Trim out the bits you don't need from here: http://www.darrenhoyt.com/2008/06/11/displaying-related-category-and-author-content-in-wordpress/

    Have a proper loop in the sidebar. Use code along these lines when using multiple loops:

    <?php $plums_loop = new WP_Query('category_name=special_cat&showposts=10'); ?>
    <?php while ($plums_loop->have_posts()) : $plums_loop->the_post(); ?>
      <!-- Do  stuff... -->
    <?php endwhile; ?>
     <?php wp_reset_query();?>
  • Reply

    You must log in to post.

    About this Topic

    Tags