WordPress show a post for each category
-
Hi all
I have searched for this, but all I found was a way to display posts by category.
I have modified the script to show the title of one post per category. But it only shows a post for the first five categories!
(I know I am doing this wrong. I should be searching for all categories, and then for each category, find the most recent post… but the script I found was for putting posts into categories… and I modified that.)
So far I have:
<div>
<?php
/* start of The Loop, Display by Category style */
if (have_posts()) :
?>
<?php
/* collect categories */
foreach($posts as $post) :
$category = get_the_category();
$cats[$category[0]->cat_ID] = $category[0]->cat_name;
endforeach;/* uncomment next line to have categories sort alphabetically */
// uasort($cats, strcasecmp);$cats = array_flip($cats);
?>
<?php
/* start of 'display by category' loop */
foreach($cats as $current_cat) :
$ItemCount = $Items;
if ($CatItem == 0 ) {
?>
<div class="item1">
<div><a class="shade" style="font-weight:bold;" href="<?php echo get_category_link($current_cat); ?>" title="View all posts in <?php echo get_the_category_by_id($current_cat); ?>"><?php echo get_the_category_by_id($current_cat); ?></a></div>
<?php
/* post loop for each category listing */foreach($posts as $post) :
the_post();
$category = get_the_category();
if($current_cat == $category[0]->cat_ID) : // if post is in correct category
if ($ItemCount != $ItemPosts ) {?>
<div class="post" id="post-<?php the_ID(); ?>"> <a href="<?php the_permalink() ?>" title="Permanent Link to <?php the_title(); ?>">
<?php the_title(); ?>
</a> </div>
<?php $ItemCount = ItemCount + 1; }
endif; // end 'if post in correct category'
endforeach; // end post loop
$CatItem = 1;
} else {
?>
<div class="item2">
<div><a class="shade" style="font-weight:bold;" href="<?php echo get_category_link($current_cat); ?>" title="View all posts in <?php echo get_the_category_by_id($current_cat); ?>"><?php echo get_the_category_by_id($current_cat); ?></a></div>
<?php
/* post loop for each category listing */foreach($posts as $post) :
the_post();
$category = get_the_category();
if($current_cat == $category[0]->cat_ID) : // if post is in correct category
if ($ItemCount != $ItemPosts ) {?>
<div class="post" id="post-<?php the_ID(); ?>"> <a href="<?php the_permalink() ?>" title="Permanent Link to <?php the_title(); ?>">
<?php the_title(); ?>
</a> </div>
<?php $ItemCount = ItemCount + 1; }
endif; // end 'if post in correct category'
endforeach; // end post loop$CatItem = 1;
}
?>
</div>
<?php
rewind_posts(); // reset loop for next category
endforeach; // end 'display by category' loop
?>
<?php endif; // end of The Loop, organized by category style
?>you can see the results at http://www.therevival.co.uk/test.php
(the top two items are from a different hack… the relevant bits are below ‘News By Region’)
The topic ‘WordPress show a post for each category’ is closed to new replies.