This function could be used to display all categories and their posts. One example of its usage is for the Archive page.
To use it copy and paste the function into the file “functions.php” located inside the “wp-content\themes\your theme” folder. You may have to create that file if it does not exist yet.
To call the function, use posts_by_cats(3), where 3 is the number of post to be displayed in each category.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | <?php /* This funtion will display posts for each parent categories */ function posts_by_cats($num_of_posts) { global $wpdb; // query the cat id // remove `parent` = 0 to display all categories $sql = "SELECT `term_id` FROM $wpdb->term_taxonomy WHERE `taxonomy`='category' AND `parent` = 0 AND `count` != 0"; $cats = $wpdb->get_results($sql, ARRAY_A); //display posts for each cat foreach ($cats as $cat) { $cat_id = $cat['term_id']; // query the cat name $sql = sprintf("SELECT `name` FROM $wpdb->terms WHERE `term_id`=%d", $cat_id); $cat_name = $wpdb->get_var($sql); echo '<p>'; echo '<h3><a href="'. get_category_link($cat_id) . '">' . $cat_name . '</a></h3>'; // query all the posts for each cat query_posts(sprintf("cat=%d&showposts=%d", $cat_id, $num_of_posts)); // the loop if (have_posts()) : echo "<ul>"; while(have_posts()) : the_post(); ?> <li><a title="<?php the_title_attribute(); ?>" href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a> <?php endwhile; echo '<li><a href="'. get_category_link($cat_id) . '">(more)</a></li>'; echo "</ul>"; endif; echo "</p>"; } } ?> </li></ul> |



