I’m trying to make a custom template for my category pages that only pulls in post under a specific category. At the moment, I am only able to pull in all post and not category specific…

My code so far….

<?php
    //Identify current Post-Category-ID
    foreach((get_the_category()) as $category)
    {
        $postcat= $category->cat_ID;
        $catname =$category->cat_name;
    }
?>
//Print category ID
<h2><?php echo $catname; ?></h2>
<?php 
$thumbnails = get_posts();
foreach ($thumbnails as $thumbnail) {
    if ( has_post_thumbnail($thumbnail->ID)) {
      echo '<li><a href="' . get_permalink( $thumbnail->ID ) . '" title="' . esc_attr( $thumbnail->post_title ) . '">';
      echo get_the_post_thumbnail($thumbnail->ID, 'full');
      echo '</a></li>';
    }
}
?>

4 Answers
4

You’ve already got code to figure out which category you want to show posts from, here is how you would grab all the posts in that category:

// create a query to grab our posts in category of ID $postcat
$q = new WP_Query(array( 'cat' => $postcat));
if($q->have_posts()){
    // foreach post found
    while($q->have_posts()){
        $q->the_post();
        // code for displaying each post goes here
    }
    // cleanup after the WP_Query, reset the post data
    wp_reset_postdata();
} else {
    // no posts were found!
}

Never use query_posts to do your queries, always check if any posts were actually found, and always cleanup after yourself.

For more arguements for queries, see here:

http://codex.wordpress.org/Class_Reference/WP_Query

Leave a Reply

Your email address will not be published. Required fields are marked *